Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.35
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.35! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.34 2012/01/06 18:13:41 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.1056.4.33 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1056.4.13 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.1056.4.25 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.1056.4.3 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.1056.4.3 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.1056.4.7 raeburn 250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 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.1056.4.8 raeburn 258: $ua->timeout(4);
1.1056.4.3 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.1056.4.7 raeburn 266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3 raeburn 267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
1.1056.4.7 raeburn 273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 274: $loncaparev = $1;
275: }
276: }
277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
278: }
279: }
280:
281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 285: if (defined($cached)) {
1.1056.4.3 raeburn 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: }
1.993 raeburn 299: }
1.1056.4.3 raeburn 300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 305: }
1.1056.4.3 raeburn 306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 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.987 raeburn 639: my ($delthis,$regexp) = @_;
1.56 www 640: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 641: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 642: "Attempt to delete from environment ".$delthis);
643: return 'error';
644: }
1.917 albertel 645: my $opened = open(my $env_file,'+<',$env{'user.environment'});
646: if ($opened
1.915 albertel 647: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 648: &&
649: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
650: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 651: foreach my $key (keys(%disk_env)) {
1.987 raeburn 652: if ($regexp) {
653: if ($key=~/^$delthis/) {
654: delete($env{$key});
655: delete($disk_env{$key});
656: }
657: } else {
658: if ($key=~/^\Q$delthis\E/) {
659: delete($env{$key});
660: delete($disk_env{$key});
661: }
662: }
1.448 albertel 663: }
1.783 albertel 664: untie(%disk_env);
1.5 www 665: }
666: return 'ok';
1.369 albertel 667: }
668:
1.790 albertel 669: sub get_env_multiple {
670: my ($name) = @_;
671: my @values;
672: if (defined($env{$name})) {
673: # exists is it an array
674: if (ref($env{$name})) {
675: @values=@{ $env{$name} };
676: } else {
677: $values[0]=$env{$name};
678: }
679: }
680: return(@values);
681: }
682:
1.958 www 683: # ------------------------------------------------------------------- Locking
684:
685: sub set_lock {
686: my ($text)=@_;
687: $locknum++;
688: my $id=$$.'-'.$locknum;
689: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
690: 'session.lock.'.$id => $text});
691: return $id;
692: }
693:
694: sub get_locks {
695: my $num=0;
696: my %texts=();
697: foreach my $lock (split(/\,/,$env{'session.locks'})) {
698: if ($lock=~/\w/) {
699: $num++;
700: $texts{$lock}=$env{'session.lock.'.$lock};
701: }
702: }
703: return ($num,%texts);
704: }
705:
706: sub remove_lock {
707: my ($id)=@_;
708: my $newlocks='';
709: foreach my $lock (split(/\,/,$env{'session.locks'})) {
710: if (($lock=~/\w/) && ($lock ne $id)) {
711: $newlocks.=','.$lock;
712: }
713: }
714: &appenv({'session.locks' => $newlocks});
715: &delenv('session.lock.'.$id);
716: }
717:
718: sub remove_all_locks {
719: my $activelocks=$env{'session.locks'};
720: foreach my $lock (split(/\,/,$env{'session.locks'})) {
721: if ($lock=~/\w/) {
722: &remove_lock($lock);
723: }
724: }
725: }
726:
727:
1.369 albertel 728: # ------------------------------------------ Find out current server userload
729: sub userload {
730: my $numusers=0;
731: {
732: opendir(LONIDS,$perlvar{'lonIDsDir'});
733: my $filename;
734: my $curtime=time;
735: while ($filename=readdir(LONIDS)) {
1.925 albertel 736: next if ($filename eq '.' || $filename eq '..');
737: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 738: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 739: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 740: }
741: closedir(LONIDS);
742: }
743: my $userloadpercent=0;
744: my $maxuserload=$perlvar{'lonUserLoadLim'};
745: if ($maxuserload) {
1.371 albertel 746: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 747: }
1.372 albertel 748: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 749: return $userloadpercent;
1.283 www 750: }
751:
752: # ------------------------------------------ Fight off request when overloaded
753:
754: sub overloaderror {
755: my ($r,$checkserver)=@_;
756: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
757: my $loadavg;
758: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 759: open(my $loadfile,'/proc/loadavg');
1.283 www 760: $loadavg=<$loadfile>;
761: $loadavg =~ s/\s.*//g;
1.285 matthew 762: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 763: close($loadfile);
1.283 www 764: } else {
765: $loadavg=&reply('load',$checkserver);
766: }
1.285 matthew 767: my $overload=$loadavg-100;
1.283 www 768: if ($overload>0) {
1.285 matthew 769: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 770: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 771: return 413;
1.283 www 772: }
773: return '';
1.5 www 774: }
1.1 albertel 775:
776: # ------------------------------ Find server with least workload from spare.tab
1.11 www 777:
1.1 albertel 778: sub spareserver {
1.1056.4.23 raeburn 779: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 780: my $spare_server;
1.370 albertel 781: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 782: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
783: : $userloadpercent;
1.1056.4.8 raeburn 784: my ($uint_dom,$remotesessions);
1.1056.4.23 raeburn 785: if (($udom ne '') && (&domain($udom) ne '')) {
786: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1.1056.4.8 raeburn 787: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.23 raeburn 788: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
1.1056.4.8 raeburn 789: $remotesessions = $udomdefaults{'remotesessions'};
790: }
1.784 albertel 791: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8 raeburn 792: if ($uint_dom) {
1.1056.4.23 raeburn 793: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
794: $try_server));
1.1056.4.8 raeburn 795: }
1.784 albertel 796: ($spare_server, $lowest_load) =
797: &compare_server_load($try_server, $spare_server, $lowest_load);
798: }
799:
800: my $found_server = ($spare_server ne '' && $lowest_load < 100);
801:
802: if (!$found_server) {
803: foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8 raeburn 804: if ($uint_dom) {
1.1056.4.23 raeburn 805: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
806: $try_server));
1.1056.4.8 raeburn 807: }
1.784 albertel 808: ($spare_server, $lowest_load) =
809: &compare_server_load($try_server, $spare_server, $lowest_load);
810: }
811: }
812:
813: if (!$want_server_name) {
1.968 raeburn 814: my $protocol = 'http';
815: if ($protocol{$spare_server} eq 'https') {
816: $protocol = $protocol{$spare_server};
817: }
1.1001 raeburn 818: if (defined($spare_server)) {
819: my $hostname = &hostname($spare_server);
1.1056.4.8 raeburn 820: if (defined($hostname)) {
1.1001 raeburn 821: $spare_server = $protocol.'://'.$hostname;
822: }
823: }
1.784 albertel 824: }
825: return $spare_server;
826: }
827:
828: sub compare_server_load {
829: my ($try_server, $spare_server, $lowest_load) = @_;
830:
831: my $loadans = &reply('load', $try_server);
832: my $userloadans = &reply('userload',$try_server);
833:
834: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.29 raeburn 835: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 836: }
837:
838: my $load;
839: if ($loadans =~ /\d/) {
840: if ($userloadans =~ /\d/) {
841: #both are numbers, pick the bigger one
842: $load = ($loadans > $userloadans) ? $loadans
843: : $userloadans;
1.411 albertel 844: } else {
1.784 albertel 845: $load = $loadans;
1.411 albertel 846: }
1.784 albertel 847: } else {
848: $load = $userloadans;
849: }
850:
851: if (($load =~ /\d/) && ($load < $lowest_load)) {
852: $spare_server = $try_server;
853: $lowest_load = $load;
1.370 albertel 854: }
1.784 albertel 855: return ($spare_server,$lowest_load);
1.202 matthew 856: }
1.914 albertel 857:
858: # --------------------------- ask offload servers if user already has a session
859: sub find_existing_session {
860: my ($udom,$uname) = @_;
861: foreach my $try_server (@{ $spareid{'primary'} },
862: @{ $spareid{'default'} }) {
863: return $try_server if (&has_user_session($try_server, $udom, $uname));
864: }
865: return;
866: }
867:
868: # -------------------------------- ask if server already has a session for user
869: sub has_user_session {
870: my ($lonid,$udom,$uname) = @_;
871: my $result = &reply(join(':','userhassession',
872: map {&escape($_)} ($udom,$uname)),$lonid);
873: return 1 if ($result eq 'ok');
874:
875: return 0;
876: }
877:
1.1056.4.3 raeburn 878: # --------- determine least loaded server in a user's domain which allows login
879:
880: sub choose_server {
1.1056.4.31 raeburn 881: my ($udom,$checkloginvia) = @_;
1.1056.4.3 raeburn 882: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
883: my %servers = &get_servers($udom);
884: my $lowest_load = 30000;
1.1056.4.31 raeburn 885: my ($login_host,$hostname,$portal_path);
1.1056.4.3 raeburn 886: foreach my $lonhost (keys(%servers)) {
1.1056.4.31 raeburn 887: my $loginvia;
888: if ($checkloginvia) {
889: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
890: if ($loginvia) {
891: my ($server,$path) = split(/:/,$loginvia);
892: ($login_host, $lowest_load) =
893: &compare_server_load($lonhost, $login_host, $lowest_load);
894: if ($login_host eq $server) {
895: $portal_path = $path;
896: }
897: } else {
898: ($login_host, $lowest_load) =
899: &compare_server_load($lonhost, $login_host, $lowest_load);
900: if ($login_host eq $lonhost) {
901: $portal_path = '';
902: }
903: }
904: } else {
1.1056.4.3 raeburn 905: ($login_host, $lowest_load) =
1.1056.4.31 raeburn 906: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1056.4.3 raeburn 907: }
908: }
909: if ($login_host ne '') {
1.1056.4.31 raeburn 910: $hostname = &hostname($login_host);
1.1056.4.3 raeburn 911: }
1.1056.4.35! raeburn 912: return ($login_host,$hostname,$portal_path);
1.1056.4.3 raeburn 913: }
914:
1.202 matthew 915: # --------------------------------------------- Try to change a user's password
916:
917: sub changepass {
1.799 raeburn 918: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 919: $currentpass = &escape($currentpass);
920: $newpass = &escape($newpass);
1.1030 raeburn 921: my $lonhost = $perlvar{'lonHostID'};
922: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 923: $server);
924: if (! $answer) {
925: &logthis("No reply on password change request to $server ".
926: "by $uname in domain $udom.");
927: } elsif ($answer =~ "^ok") {
928: &logthis("$uname in $udom successfully changed their password ".
929: "on $server.");
930: } elsif ($answer =~ "^pwchange_failure") {
931: &logthis("$uname in $udom was unable to change their password ".
932: "on $server. The action was blocked by either lcpasswd ".
933: "or pwchange");
934: } elsif ($answer =~ "^non_authorized") {
935: &logthis("$uname in $udom did not get their password correct when ".
936: "attempting to change it on $server.");
937: } elsif ($answer =~ "^auth_mode_error") {
938: &logthis("$uname in $udom attempted to change their password despite ".
939: "not being locally or internally authenticated on $server.");
940: } elsif ($answer =~ "^unknown_user") {
941: &logthis("$uname in $udom attempted to change their password ".
942: "on $server but were unable to because $server is not ".
943: "their home server.");
944: } elsif ($answer =~ "^refused") {
945: &logthis("$server refused to change $uname in $udom password because ".
946: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 947: } elsif ($answer =~ "invalid_client") {
948: &logthis("$server refused to change $uname in $udom password because ".
949: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 950: }
951: return $answer;
1.1 albertel 952: }
953:
1.169 harris41 954: # ----------------------- Try to determine user's current authentication scheme
955:
956: sub queryauthenticate {
957: my ($uname,$udom)=@_;
1.456 albertel 958: my $uhome=&homeserver($uname,$udom);
959: if (!$uhome) {
960: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
961: return 'no_host';
962: }
963: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
964: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
965: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 966: }
1.456 albertel 967: return $answer;
1.169 harris41 968: }
969:
1.1 albertel 970: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 971:
1.1 albertel 972: sub authenticate {
1.1056.4.3 raeburn 973: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 974: $upass=&escape($upass);
975: $uname= &LONCAPA::clean_username($uname);
1.836 www 976: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 977: my $newhome;
1.836 www 978: if ((!$uhome) || ($uhome eq 'no_host')) {
979: # Maybe the machine was offline and only re-appeared again recently?
980: &reconlonc();
981: # One more
1.952 raeburn 982: $uhome=&homeserver($uname,$udom,1);
983: if (($uhome eq 'no_host') && $checkdefauth) {
984: if (defined(&domain($udom,'primary'))) {
985: $newhome=&domain($udom,'primary');
986: }
987: if ($newhome ne '') {
988: $uhome = $newhome;
989: }
990: }
1.836 www 991: if ((!$uhome) || ($uhome eq 'no_host')) {
992: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 993: return 'no_host';
994: }
1.1 albertel 995: }
1.1056.4.3 raeburn 996: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 997: if ($answer eq 'authorized') {
1.952 raeburn 998: if ($newhome) {
999: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1000: return 'no_account_on_host';
1001: } else {
1002: &logthis("User $uname at $udom authorized by $uhome");
1003: return $uhome;
1004: }
1.471 albertel 1005: }
1006: if ($answer eq 'non_authorized') {
1007: &logthis("User $uname at $udom rejected by $uhome");
1008: return 'no_host';
1.9 www 1009: }
1.471 albertel 1010: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1011: return 'no_host';
1012: }
1013:
1.1056.4.3 raeburn 1014: sub can_host_session {
1015: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1016: my $canhost = 1;
1017: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1018: if (ref($remotesessions) eq 'HASH') {
1019: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1020: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1021: $canhost = 0;
1022: } else {
1023: $canhost = 1;
1024: }
1025: }
1026: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1027: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1028: $canhost = 1;
1029: } else {
1030: $canhost = 0;
1031: }
1032: }
1033: if ($canhost) {
1034: if ($remotesessions->{'version'} ne '') {
1035: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1036: if ($reqmajor ne '' && $reqminor ne '') {
1037: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1038: my $major = $1;
1039: my $minor = $2;
1040: if (($major < $reqmajor ) ||
1041: (($major == $reqmajor) && ($minor < $reqminor))) {
1042: $canhost = 0;
1043: }
1044: } else {
1045: $canhost = 0;
1046: }
1047: }
1048: }
1049: }
1050: }
1051: if ($canhost) {
1052: if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28 raeburn 1053: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1054: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3 raeburn 1055: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28 raeburn 1056: if (($uint_dom ne '') &&
1057: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3 raeburn 1058: $canhost = 0;
1059: } else {
1060: $canhost = 1;
1061: }
1062: }
1063: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28 raeburn 1064: if (($uint_dom ne '') &&
1065: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3 raeburn 1066: $canhost = 1;
1067: } else {
1068: $canhost = 0;
1069: }
1070: }
1071: }
1072: }
1073: return $canhost;
1074: }
1075:
1.1056.4.8 raeburn 1076: sub spare_can_host {
1077: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1078: my $canhost=1;
1079: my @intdoms;
1080: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1081: if (ref($internet_names) eq 'ARRAY') {
1082: @intdoms = @{$internet_names};
1083: }
1084: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1085: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1086: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1087: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1088: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1089: $canhost = &can_host_session($udom,$try_server,$remoterev,
1090: $remotesessions,
1091: $defdomdefaults{'hostedsessions'});
1092: }
1093: return $canhost;
1094: }
1095:
1.1 albertel 1096: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1097:
1.599 albertel 1098: my %homecache;
1.1 albertel 1099: sub homeserver {
1.230 stredwic 1100: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1101: my $index="$uname:$udom";
1.426 albertel 1102:
1.599 albertel 1103: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1104:
1105: my %servers = &get_servers($udom,'library');
1106: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1107: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1108: exists($badServerCache{$tryserver}));
1.841 albertel 1109:
1110: my $answer=reply("home:$udom:$uname",$tryserver);
1111: if ($answer eq 'found') {
1112: delete($badServerCache{$tryserver});
1113: return $homecache{$index}=$tryserver;
1114: } elsif ($answer eq 'no_host') {
1115: $badServerCache{$tryserver}=1;
1116: }
1.1 albertel 1117: }
1118: return 'no_host';
1.70 www 1119: }
1120:
1121: # ------------------------------------- Find the usernames behind a list of IDs
1122:
1123: sub idget {
1124: my ($udom,@ids)=@_;
1125: my %returnhash=();
1126:
1.841 albertel 1127: my %servers = &get_servers($udom,'library');
1128: foreach my $tryserver (keys(%servers)) {
1129: my $idlist=join('&',@ids);
1130: $idlist=~tr/A-Z/a-z/;
1131: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1132: my @answer=();
1133: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1134: @answer=split(/\&/,$reply);
1135: } ;
1136: my $i;
1137: for ($i=0;$i<=$#ids;$i++) {
1138: if ($answer[$i]) {
1139: $returnhash{$ids[$i]}=$answer[$i];
1140: }
1141: }
1142: }
1.70 www 1143: return %returnhash;
1144: }
1145:
1146: # ------------------------------------- Find the IDs behind a list of usernames
1147:
1148: sub idrget {
1149: my ($udom,@unames)=@_;
1150: my %returnhash=();
1.800 albertel 1151: foreach my $uname (@unames) {
1152: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1153: }
1.70 www 1154: return %returnhash;
1155: }
1156:
1157: # ------------------------------- Store away a list of names and associated IDs
1158:
1159: sub idput {
1160: my ($udom,%ids)=@_;
1161: my %servers=();
1.800 albertel 1162: foreach my $uname (keys(%ids)) {
1163: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1164: my $uhom=&homeserver($uname,$udom);
1.70 www 1165: if ($uhom ne 'no_host') {
1.800 albertel 1166: my $id=&escape($ids{$uname});
1.70 www 1167: $id=~tr/A-Z/a-z/;
1.800 albertel 1168: my $esc_unam=&escape($uname);
1.70 www 1169: if ($servers{$uhom}) {
1.800 albertel 1170: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1171: } else {
1.800 albertel 1172: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1173: }
1174: }
1.191 harris41 1175: }
1.800 albertel 1176: foreach my $server (keys(%servers)) {
1177: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1178: }
1.344 www 1179: }
1180:
1.1023 raeburn 1181: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1182: sub dump_dom {
1.1023 raeburn 1183: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1184: if (!$udom) {
1185: $udom=$env{'user.domain'};
1186: }
1187: my %returnhash;
1.1023 raeburn 1188: if ($udom) {
1189: my $uname = &get_domainconfiguser($udom);
1190: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1191: }
1192: return %returnhash;
1193: }
1194:
1.1023 raeburn 1195: # ------------------------------------------ get items from domain db files
1.806 raeburn 1196:
1197: sub get_dom {
1.860 raeburn 1198: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1199: my $items='';
1200: foreach my $item (@$storearr) {
1201: $items.=&escape($item).'&';
1202: }
1203: $items=~s/\&$//;
1.860 raeburn 1204: if (!$udom) {
1205: $udom=$env{'user.domain'};
1206: if (defined(&domain($udom,'primary'))) {
1207: $uhome=&domain($udom,'primary');
1208: } else {
1.874 albertel 1209: undef($uhome);
1.860 raeburn 1210: }
1211: } else {
1212: if (!$uhome) {
1213: if (defined(&domain($udom,'primary'))) {
1214: $uhome=&domain($udom,'primary');
1215: }
1216: }
1217: }
1218: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1219: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1220: my %returnhash;
1.875 albertel 1221: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1222: return %returnhash;
1223: }
1.806 raeburn 1224: my @pairs=split(/\&/,$rep);
1225: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1226: return @pairs;
1227: }
1228: my $i=0;
1229: foreach my $item (@$storearr) {
1230: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1231: $i++;
1232: }
1233: return %returnhash;
1234: } else {
1.880 banghart 1235: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1236: }
1237: }
1238:
1239: # -------------------------------------------- put items in domain db files
1240:
1241: sub put_dom {
1.860 raeburn 1242: my ($namespace,$storehash,$udom,$uhome)=@_;
1243: if (!$udom) {
1244: $udom=$env{'user.domain'};
1245: if (defined(&domain($udom,'primary'))) {
1246: $uhome=&domain($udom,'primary');
1247: } else {
1.874 albertel 1248: undef($uhome);
1.860 raeburn 1249: }
1250: } else {
1251: if (!$uhome) {
1252: if (defined(&domain($udom,'primary'))) {
1253: $uhome=&domain($udom,'primary');
1254: }
1255: }
1256: }
1257: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1258: my $items='';
1259: foreach my $item (keys(%$storehash)) {
1260: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1261: }
1262: $items=~s/\&$//;
1263: return &reply("putdom:$udom:$namespace:$items",$uhome);
1264: } else {
1.860 raeburn 1265: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1266: }
1267: }
1268:
1.1023 raeburn 1269: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1270: sub newput_dom {
1.1023 raeburn 1271: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1272: my $result;
1273: if (!$udom) {
1274: $udom=$env{'user.domain'};
1275: }
1.1023 raeburn 1276: if ($udom) {
1277: my $uname = &get_domainconfiguser($udom);
1278: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1279: }
1280: return $result;
1281: }
1282:
1.1023 raeburn 1283: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1284: sub del_dom {
1.1023 raeburn 1285: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1286: if (ref($storearr) eq 'ARRAY') {
1287: if (!$udom) {
1288: $udom=$env{'user.domain'};
1289: }
1.1023 raeburn 1290: if ($udom) {
1291: my $uname = &get_domainconfiguser($udom);
1292: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1293: }
1294: }
1295: }
1296:
1.1023 raeburn 1297: # ----------------------------------construct domainconfig user for a domain
1298: sub get_domainconfiguser {
1299: my ($udom) = @_;
1300: return $udom.'-domainconfig';
1301: }
1302:
1.837 raeburn 1303: sub retrieve_inst_usertypes {
1304: my ($udom) = @_;
1305: my (%returnhash,@order);
1.989 raeburn 1306: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1307: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1308: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1309: %returnhash = %{$domdefs{'inststatustypes'}};
1310: @order = @{$domdefs{'inststatusorder'}};
1311: } else {
1312: if (defined(&domain($udom,'primary'))) {
1313: my $uhome=&domain($udom,'primary');
1314: my $rep=&reply("inst_usertypes:$udom",$uhome);
1315: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1316: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1317: return (\%returnhash,\@order);
1318: }
1319: my ($hashitems,$orderitems) = split(/:/,$rep);
1320: my @pairs=split(/\&/,$hashitems);
1321: foreach my $item (@pairs) {
1322: my ($key,$value)=split(/=/,$item,2);
1323: $key = &unescape($key);
1324: next if ($key =~ /^error: 2 /);
1325: $returnhash{$key}=&thaw_unescape($value);
1326: }
1327: my @esc_order = split(/\&/,$orderitems);
1328: foreach my $item (@esc_order) {
1329: push(@order,&unescape($item));
1330: }
1331: } else {
1332: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1333: }
1334: }
1335: return (\%returnhash,\@order);
1336: }
1337:
1.868 raeburn 1338: sub is_domainimage {
1339: my ($url) = @_;
1340: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1341: if (&domain($1) ne '') {
1342: return '1';
1343: }
1344: }
1345: return;
1346: }
1347:
1.899 raeburn 1348: sub inst_directory_query {
1349: my ($srch) = @_;
1350: my $udom = $srch->{'srchdomain'};
1351: my %results;
1352: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1353: my $outcome;
1.899 raeburn 1354: if ($homeserver ne '') {
1.904 albertel 1355: my $queryid=&reply("querysend:instdirsearch:".
1356: &escape($srch->{'srchby'}).':'.
1357: &escape($srch->{'srchterm'}).':'.
1358: &escape($srch->{'srchtype'}),$homeserver);
1359: my $host=&hostname($homeserver);
1360: if ($queryid !~/^\Q$host\E\_/) {
1361: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1362: return;
1363: }
1364: my $response = &get_query_reply($queryid);
1365: my $maxtries = 5;
1366: my $tries = 1;
1367: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1368: $response = &get_query_reply($queryid);
1369: $tries ++;
1370: }
1371:
1372: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1373: if ($response eq 'unavailable') {
1374: $outcome = $response;
1375: } else {
1376: $outcome = 'ok';
1377: my @matches = split(/\n/,$response);
1378: foreach my $match (@matches) {
1379: my ($key,$value) = split(/=/,$match);
1380: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1381: }
1.899 raeburn 1382: }
1383: }
1384: }
1.909 raeburn 1385: return ($outcome,%results);
1.899 raeburn 1386: }
1387:
1388: sub usersearch {
1389: my ($srch) = @_;
1390: my $dom = $srch->{'srchdomain'};
1391: my %results;
1392: my %libserv = &all_library();
1393: my $query = 'usersearch';
1394: foreach my $tryserver (keys(%libserv)) {
1395: if (&host_domain($tryserver) eq $dom) {
1396: my $host=&hostname($tryserver);
1397: my $queryid=
1.911 raeburn 1398: &reply("querysend:".&escape($query).':'.
1399: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1400: &escape($srch->{'srchtype'}).':'.
1401: &escape($srch->{'srchterm'}),$tryserver);
1402: if ($queryid !~/^\Q$host\E\_/) {
1403: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1404: next;
1.899 raeburn 1405: }
1406: my $reply = &get_query_reply($queryid);
1407: my $maxtries = 1;
1408: my $tries = 1;
1409: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1410: $reply = &get_query_reply($queryid);
1411: $tries ++;
1412: }
1413: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1414: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1415: } else {
1.911 raeburn 1416: my @matches;
1417: if ($reply =~ /\n/) {
1418: @matches = split(/\n/,$reply);
1419: } else {
1420: @matches = split(/\&/,$reply);
1421: }
1.899 raeburn 1422: foreach my $match (@matches) {
1423: my ($uname,$udom,%userhash);
1.911 raeburn 1424: foreach my $entry (split(/:/,$match)) {
1425: my ($key,$value) =
1426: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1427: $userhash{$key} = $value;
1428: if ($key eq 'username') {
1429: $uname = $value;
1430: } elsif ($key eq 'domain') {
1431: $udom = $value;
1.911 raeburn 1432: }
1.899 raeburn 1433: }
1434: $results{$uname.':'.$udom} = \%userhash;
1435: }
1436: }
1437: }
1438: }
1439: return %results;
1440: }
1441:
1.912 raeburn 1442: sub get_instuser {
1443: my ($udom,$uname,$id) = @_;
1444: my $homeserver = &domain($udom,'primary');
1445: my ($outcome,%results);
1446: if ($homeserver ne '') {
1447: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1448: &escape($id).':'.&escape($udom),$homeserver);
1449: my $host=&hostname($homeserver);
1450: if ($queryid !~/^\Q$host\E\_/) {
1451: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1452: return;
1453: }
1454: my $response = &get_query_reply($queryid);
1455: my $maxtries = 5;
1456: my $tries = 1;
1457: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1458: $response = &get_query_reply($queryid);
1459: $tries ++;
1460: }
1461: if (!&error($response) && $response ne 'refused') {
1462: if ($response eq 'unavailable') {
1463: $outcome = $response;
1464: } else {
1465: $outcome = 'ok';
1466: my @matches = split(/\n/,$response);
1467: foreach my $match (@matches) {
1468: my ($key,$value) = split(/=/,$match);
1469: $results{&unescape($key)} = &thaw_unescape($value);
1470: }
1471: }
1472: }
1473: }
1474: my %userinfo;
1475: if (ref($results{$uname}) eq 'HASH') {
1476: %userinfo = %{$results{$uname}};
1477: }
1478: return ($outcome,%userinfo);
1479: }
1480:
1481: sub inst_rulecheck {
1.923 raeburn 1482: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1483: my %returnhash;
1484: if ($udom ne '') {
1485: if (ref($rules) eq 'ARRAY') {
1486: @{$rules} = map {&escape($_);} (@{$rules});
1487: my $rulestr = join(':',@{$rules});
1488: my $homeserver=&domain($udom,'primary');
1489: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1490: my $response;
1491: if ($item eq 'username') {
1492: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1493: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1494: $homeserver));
1.923 raeburn 1495: } elsif ($item eq 'id') {
1496: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1497: ':'.&escape($id).':'.$rulestr,
1498: $homeserver));
1.945 raeburn 1499: } elsif ($item eq 'selfcreate') {
1500: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1501: &escape($udom).':'.&escape($uname).
1502: ':'.$rulestr,$homeserver));
1.923 raeburn 1503: }
1.912 raeburn 1504: if ($response ne 'refused') {
1505: my @pairs=split(/\&/,$response);
1506: foreach my $item (@pairs) {
1507: my ($key,$value)=split(/=/,$item,2);
1508: $key = &unescape($key);
1509: next if ($key =~ /^error: 2 /);
1510: $returnhash{$key}=&thaw_unescape($value);
1511: }
1512: }
1513: }
1514: }
1515: }
1516: return %returnhash;
1517: }
1518:
1519: sub inst_userrules {
1.923 raeburn 1520: my ($udom,$check) = @_;
1.912 raeburn 1521: my (%ruleshash,@ruleorder);
1522: if ($udom ne '') {
1523: my $homeserver=&domain($udom,'primary');
1524: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1525: my $response;
1526: if ($check eq 'id') {
1527: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1528: $homeserver);
1.943 raeburn 1529: } elsif ($check eq 'email') {
1530: $response=&reply('instemailrules:'.&escape($udom),
1531: $homeserver);
1.923 raeburn 1532: } else {
1533: $response=&reply('instuserrules:'.&escape($udom),
1534: $homeserver);
1535: }
1.912 raeburn 1536: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1537: ($response ne 'unknown_cmd') &&
1.912 raeburn 1538: ($response ne 'no_such_host')) {
1539: my ($hashitems,$orderitems) = split(/:/,$response);
1540: my @pairs=split(/\&/,$hashitems);
1541: foreach my $item (@pairs) {
1542: my ($key,$value)=split(/=/,$item,2);
1543: $key = &unescape($key);
1544: next if ($key =~ /^error: 2 /);
1545: $ruleshash{$key}=&thaw_unescape($value);
1546: }
1547: my @esc_order = split(/\&/,$orderitems);
1548: foreach my $item (@esc_order) {
1549: push(@ruleorder,&unescape($item));
1550: }
1551: }
1552: }
1553: }
1554: return (\%ruleshash,\@ruleorder);
1555: }
1556:
1.976 raeburn 1557: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1558:
1559: sub get_domain_defaults {
1560: my ($domain) = @_;
1561: my $cachetime = 60*60*24;
1562: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1563: if (defined($cached)) {
1564: if (ref($result) eq 'HASH') {
1565: return %{$result};
1566: }
1567: }
1568: my %domdefaults;
1569: my %domconfig =
1.989 raeburn 1570: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1571: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1572: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1573: if (ref($domconfig{'defaults'}) eq 'HASH') {
1574: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1575: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1576: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1577: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1578: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1056.4.34 raeburn 1579: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1580: } else {
1581: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1582: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1583: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1584: }
1.976 raeburn 1585: if (ref($domconfig{'quotas'}) eq 'HASH') {
1586: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1587: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1588: } else {
1589: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1590: }
1591: my @usertools = ('aboutme','blog','portfolio');
1592: foreach my $item (@usertools) {
1593: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1594: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1595: }
1596: }
1597: }
1.985 raeburn 1598: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1599: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1600: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1601: }
1602: }
1.989 raeburn 1603: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1604: foreach my $item ('inststatustypes','inststatusorder') {
1605: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1606: }
1607: }
1.1047 raeburn 1608: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1609: foreach my $item ('canuse_pdfforms') {
1610: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1611: }
1612: }
1.1056.4.3 raeburn 1613: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1614: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1615: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1616: }
1617: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1618: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1619: }
1620: }
1.943 raeburn 1621: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1622: $cachetime);
1623: return %domdefaults;
1624: }
1625:
1.344 www 1626: # --------------------------------------------------- Assign a key to a student
1627:
1628: sub assign_access_key {
1.364 www 1629: #
1630: # a valid key looks like uname:udom#comments
1631: # comments are being appended
1632: #
1.498 www 1633: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1634: $kdom=
1.620 albertel 1635: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1636: $knum=
1.620 albertel 1637: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1638: $cdom=
1.620 albertel 1639: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1640: $cnum=
1.620 albertel 1641: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1642: $udom=$env{'user.name'} unless (defined($udom));
1643: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1644: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1645: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1646: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1647: # assigned to this person
1648: # - this should not happen,
1.345 www 1649: # unless something went wrong
1650: # the first time around
1651: # ready to assign
1.364 www 1652: $logentry=$1.'; '.$logentry;
1.496 www 1653: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1654: $kdom,$knum) eq 'ok') {
1.345 www 1655: # key now belongs to user
1.346 www 1656: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1657: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1658: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1659: return 'ok';
1660: } else {
1661: return
1662: 'error: Count not permanently assign key, will need to be re-entered later.';
1663: }
1664: } else {
1665: return 'error: Could not assign key, try again later.';
1666: }
1.364 www 1667: } elsif (!$existing{$ckey}) {
1.345 www 1668: # the key does not exist
1669: return 'error: The key does not exist';
1670: } else {
1671: # the key is somebody else's
1672: return 'error: The key is already in use';
1673: }
1.344 www 1674: }
1675:
1.364 www 1676: # ------------------------------------------ put an additional comment on a key
1677:
1678: sub comment_access_key {
1679: #
1680: # a valid key looks like uname:udom#comments
1681: # comments are being appended
1682: #
1683: my ($ckey,$cdom,$cnum,$logentry)=@_;
1684: $cdom=
1.620 albertel 1685: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1686: $cnum=
1.620 albertel 1687: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1688: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1689: if ($existing{$ckey}) {
1690: $existing{$ckey}.='; '.$logentry;
1691: # ready to assign
1.367 www 1692: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1693: $cdom,$cnum) eq 'ok') {
1694: return 'ok';
1695: } else {
1696: return 'error: Count not store comment.';
1697: }
1698: } else {
1699: # the key does not exist
1700: return 'error: The key does not exist';
1701: }
1702: }
1703:
1.344 www 1704: # ------------------------------------------------------ Generate a set of keys
1705:
1706: sub generate_access_keys {
1.364 www 1707: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1708: $cdom=
1.620 albertel 1709: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1710: $cnum=
1.620 albertel 1711: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1712: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1713: unless (($cdom) && ($cnum)) { return 0; }
1714: if ($number>10000) { return 0; }
1715: sleep(2); # make sure don't get same seed twice
1716: srand(time()^($$+($$<<15))); # from "Programming Perl"
1717: my $total=0;
1718: for (my $i=1;$i<=$number;$i++) {
1719: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1720: sprintf("%lx",int(100000*rand)).'-'.
1721: sprintf("%lx",int(100000*rand));
1722: $newkey=~s/1/g/g; # folks mix up 1 and l
1723: $newkey=~s/0/h/g; # and also 0 and O
1724: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1725: if ($existing{$newkey}) {
1726: $i--;
1727: } else {
1.364 www 1728: if (&put('accesskeys',
1729: { $newkey => '# generated '.localtime().
1.620 albertel 1730: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1731: '; '.$logentry },
1732: $cdom,$cnum) eq 'ok') {
1.344 www 1733: $total++;
1734: }
1735: }
1736: }
1.620 albertel 1737: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1738: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1739: return $total;
1740: }
1741:
1742: # ------------------------------------------------------- Validate an accesskey
1743:
1744: sub validate_access_key {
1745: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1746: $cdom=
1.620 albertel 1747: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1748: $cnum=
1.620 albertel 1749: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1750: $udom=$env{'user.domain'} unless (defined($udom));
1751: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1752: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1753: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1754: }
1755:
1756: # ------------------------------------- Find the section of student in a course
1.652 albertel 1757: sub devalidate_getsection_cache {
1758: my ($udom,$unam,$courseid)=@_;
1759: my $hashid="$udom:$unam:$courseid";
1760: &devalidate_cache_new('getsection',$hashid);
1761: }
1.298 matthew 1762:
1.815 albertel 1763: sub courseid_to_courseurl {
1764: my ($courseid) = @_;
1765: #already url style courseid
1766: return $courseid if ($courseid =~ m{^/});
1767:
1768: if (exists($env{'course.'.$courseid.'.num'})) {
1769: my $cnum = $env{'course.'.$courseid.'.num'};
1770: my $cdom = $env{'course.'.$courseid.'.domain'};
1771: return "/$cdom/$cnum";
1772: }
1773:
1774: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1775: if (exists($courseinfo{'num'})) {
1776: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1777: }
1778:
1779: return undef;
1780: }
1781:
1.298 matthew 1782: sub getsection {
1783: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1784: my $cachetime=1800;
1.551 albertel 1785:
1786: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1787: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1788: if (defined($cached)) { return $result; }
1789:
1.298 matthew 1790: my %Pending;
1791: my %Expired;
1792: #
1793: # Each role can either have not started yet (pending), be active,
1794: # or have expired.
1795: #
1796: # If there is an active role, we are done.
1797: #
1798: # If there is more than one role which has not started yet,
1799: # choose the one which will start sooner
1800: # If there is one role which has not started yet, return it.
1801: #
1802: # If there is more than one expired role, choose the one which ended last.
1803: # If there is a role which has expired, return it.
1804: #
1.815 albertel 1805: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1806: my $extra = &freeze_escape({'skipcheck' => 1});
1807: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1808: foreach my $key (keys(%roleshash)) {
1.479 albertel 1809: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1810: my $section=$1;
1811: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1812: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1813: my $now=time;
1.548 albertel 1814: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1815: $Expired{$end}=$section;
1816: next;
1817: }
1.548 albertel 1818: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1819: $Pending{$start}=$section;
1820: next;
1821: }
1.599 albertel 1822: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1823: }
1824: #
1825: # Presumedly there will be few matching roles from the above
1826: # loop and the sorting time will be negligible.
1827: if (scalar(keys(%Pending))) {
1828: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1829: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1830: }
1831: if (scalar(keys(%Expired))) {
1832: my @sorted = sort {$a <=> $b} keys(%Expired);
1833: my $time = pop(@sorted);
1.599 albertel 1834: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1835: }
1.599 albertel 1836: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1837: }
1.70 www 1838:
1.599 albertel 1839: sub save_cache {
1840: &purge_remembered();
1.722 albertel 1841: #&Apache::loncommon::validate_page();
1.620 albertel 1842: undef(%env);
1.780 albertel 1843: undef($env_loaded);
1.599 albertel 1844: }
1.452 albertel 1845:
1.599 albertel 1846: my $to_remember=-1;
1847: my %remembered;
1848: my %accessed;
1849: my $kicks=0;
1850: my $hits=0;
1.849 albertel 1851: sub make_key {
1852: my ($name,$id) = @_;
1.872 albertel 1853: if (length($id) > 65
1854: && length(&escape($id)) > 200) {
1855: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1856: }
1.849 albertel 1857: return &escape($name.':'.$id);
1858: }
1859:
1.599 albertel 1860: sub devalidate_cache_new {
1861: my ($name,$id,$debug) = @_;
1862: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1863: $id=&make_key($name,$id);
1.599 albertel 1864: $memcache->delete($id);
1865: delete($remembered{$id});
1866: delete($accessed{$id});
1867: }
1868:
1869: sub is_cached_new {
1870: my ($name,$id,$debug) = @_;
1.849 albertel 1871: $id=&make_key($name,$id);
1.599 albertel 1872: if (exists($remembered{$id})) {
1873: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1874: $accessed{$id}=[&gettimeofday()];
1875: $hits++;
1876: return ($remembered{$id},1);
1877: }
1878: my $value = $memcache->get($id);
1879: if (!(defined($value))) {
1880: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1881: return (undef,undef);
1.416 albertel 1882: }
1.599 albertel 1883: if ($value eq '__undef__') {
1884: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1885: $value=undef;
1886: }
1887: &make_room($id,$value,$debug);
1888: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1889: return ($value,1);
1890: }
1891:
1892: sub do_cache_new {
1893: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1894: $id=&make_key($name,$id);
1.599 albertel 1895: my $setvalue=$value;
1896: if (!defined($setvalue)) {
1897: $setvalue='__undef__';
1898: }
1.623 albertel 1899: if (!defined($time) ) {
1900: $time=600;
1901: }
1.599 albertel 1902: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1903: my $result = $memcache->set($id,$setvalue,$time);
1904: if (! $result) {
1.872 albertel 1905: &logthis("caching of id -> $id failed");
1.910 albertel 1906: $memcache->disconnect_all();
1.872 albertel 1907: }
1.600 albertel 1908: # need to make a copy of $value
1.919 albertel 1909: &make_room($id,$value,$debug);
1.599 albertel 1910: return $value;
1911: }
1912:
1913: sub make_room {
1914: my ($id,$value,$debug)=@_;
1.919 albertel 1915:
1916: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1917: : $value;
1.599 albertel 1918: if ($to_remember<0) { return; }
1919: $accessed{$id}=[&gettimeofday()];
1920: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1921: my $to_kick;
1922: my $max_time=0;
1923: foreach my $other (keys(%accessed)) {
1924: if (&tv_interval($accessed{$other}) > $max_time) {
1925: $to_kick=$other;
1926: $max_time=&tv_interval($accessed{$other});
1927: }
1928: }
1929: delete($remembered{$to_kick});
1930: delete($accessed{$to_kick});
1931: $kicks++;
1932: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1933: return;
1934: }
1935:
1.599 albertel 1936: sub purge_remembered {
1.604 albertel 1937: #&logthis("Tossing ".scalar(keys(%remembered)));
1938: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1939: undef(%remembered);
1940: undef(%accessed);
1.428 albertel 1941: }
1.70 www 1942: # ------------------------------------- Read an entry from a user's environment
1943:
1944: sub userenvironment {
1945: my ($udom,$unam,@what)=@_;
1.976 raeburn 1946: my $items;
1947: foreach my $item (@what) {
1948: $items.=&escape($item).'&';
1949: }
1950: $items=~s/\&$//;
1.70 www 1951: my %returnhash=();
1.1009 raeburn 1952: my $uhome = &homeserver($unam,$udom);
1953: unless ($uhome eq 'no_host') {
1954: my @answer=split(/\&/,
1955: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1956: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1957: return %returnhash;
1958: }
1.1009 raeburn 1959: my $i;
1960: for ($i=0;$i<=$#what;$i++) {
1961: $returnhash{$what[$i]}=&unescape($answer[$i]);
1962: }
1.70 www 1963: }
1964: return %returnhash;
1.1 albertel 1965: }
1966:
1.617 albertel 1967: # ---------------------------------------------------------- Get a studentphoto
1968: sub studentphoto {
1969: my ($udom,$unam,$ext) = @_;
1970: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1971: if (defined($env{'request.course.id'})) {
1.708 raeburn 1972: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1973: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1974: return(&retrievestudentphoto($udom,$unam,$ext));
1975: } else {
1976: my ($result,$perm_reqd)=
1.707 albertel 1977: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1978: if ($result eq 'ok') {
1979: if (!($perm_reqd eq 'yes')) {
1980: return(&retrievestudentphoto($udom,$unam,$ext));
1981: }
1982: }
1983: }
1984: }
1985: } else {
1986: my ($result,$perm_reqd) =
1.707 albertel 1987: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1988: if ($result eq 'ok') {
1989: if (!($perm_reqd eq 'yes')) {
1990: return(&retrievestudentphoto($udom,$unam,$ext));
1991: }
1992: }
1993: }
1994: return '/adm/lonKaputt/lonlogo_broken.gif';
1995: }
1996:
1997: sub retrievestudentphoto {
1998: my ($udom,$unam,$ext,$type) = @_;
1999: my $home=&Apache::lonnet::homeserver($unam,$udom);
2000: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2001: if ($ret eq 'ok') {
2002: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2003: if ($type eq 'thumbnail') {
2004: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2005: }
2006: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2007: return $tokenurl;
2008: } else {
2009: if ($type eq 'thumbnail') {
2010: return '/adm/lonKaputt/genericstudent_tn.gif';
2011: } else {
2012: return '/adm/lonKaputt/lonlogo_broken.gif';
2013: }
1.617 albertel 2014: }
2015: }
2016:
1.263 www 2017: # -------------------------------------------------------------------- New chat
2018:
2019: sub chatsend {
1.724 raeburn 2020: my ($newentry,$anon,$group)=@_;
1.620 albertel 2021: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2022: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2023: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2024: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2025: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2026: &escape($newentry)).':'.$group,$chome);
1.292 www 2027: }
2028:
2029: # ------------------------------------------ Find current version of a resource
2030:
2031: sub getversion {
2032: my $fname=&clutter(shift);
2033: unless ($fname=~/^\/res\//) { return -1; }
2034: return ¤tversion(&filelocation('',$fname));
2035: }
2036:
2037: sub currentversion {
2038: my $fname=shift;
1.599 albertel 2039: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 2040: if (defined($cached)) { return $result; }
1.292 www 2041: my $author=$fname;
2042: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2043: my ($udom,$uname)=split(/\//,$author);
2044: my $home=homeserver($uname,$udom);
2045: if ($home eq 'no_host') {
2046: return -1;
2047: }
2048: my $answer=reply("currentversion:$fname",$home);
2049: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2050: return -1;
2051: }
1.599 albertel 2052: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2053: }
2054:
1.1 albertel 2055: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2056:
1.1 albertel 2057: sub subscribe {
2058: my $fname=shift;
1.761 raeburn 2059: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2060: $fname=~s/[\n\r]//g;
1.1 albertel 2061: my $author=$fname;
2062: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2063: my ($udom,$uname)=split(/\//,$author);
2064: my $home=homeserver($uname,$udom);
1.335 albertel 2065: if ($home eq 'no_host') {
2066: return 'not_found';
1.1 albertel 2067: }
2068: my $answer=reply("sub:$fname",$home);
1.64 www 2069: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2070: $answer.=' by '.$home;
2071: }
1.1 albertel 2072: return $answer;
2073: }
2074:
1.8 www 2075: # -------------------------------------------------------------- Replicate file
2076:
2077: sub repcopy {
2078: my $filename=shift;
1.23 www 2079: $filename=~s/\/+/\//g;
1.607 raeburn 2080: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2081: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2082: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2083: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2084: return &repcopy_userfile($filename);
2085: }
1.532 albertel 2086: $filename=~s/[\n\r]//g;
1.8 www 2087: my $transname="$filename.in.transfer";
1.828 www 2088: # FIXME: this should flock
1.607 raeburn 2089: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2090: my $remoteurl=subscribe($filename);
1.64 www 2091: if ($remoteurl =~ /^con_lost by/) {
2092: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2093: return 'unavailable';
1.8 www 2094: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2095: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2096: return 'not_found';
1.64 www 2097: } elsif ($remoteurl =~ /^rejected by/) {
2098: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2099: return 'forbidden';
1.20 www 2100: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2101: return 'ok';
1.8 www 2102: } else {
1.290 www 2103: my $author=$filename;
2104: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2105: my ($udom,$uname)=split(/\//,$author);
2106: my $home=homeserver($uname,$udom);
2107: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2108: my @parts=split(/\//,$filename);
2109: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2110: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2111: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2112: return 'bad_request';
1.8 www 2113: }
2114: my $count;
2115: for ($count=5;$count<$#parts;$count++) {
2116: $path.="/$parts[$count]";
2117: if ((-e $path)!=1) {
2118: mkdir($path,0777);
2119: }
2120: }
2121: my $ua=new LWP::UserAgent;
2122: my $request=new HTTP::Request('GET',"$remoteurl");
2123: my $response=$ua->request($request,$transname);
2124: if ($response->is_error()) {
2125: unlink($transname);
2126: my $message=$response->status_line;
1.672 albertel 2127: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2128: ." LWP get: $message: $filename</font>");
1.607 raeburn 2129: return 'unavailable';
1.8 www 2130: } else {
1.16 www 2131: if ($remoteurl!~/\.meta$/) {
2132: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2133: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2134: if ($mresponse->is_error()) {
2135: unlink($filename.'.meta');
2136: &logthis(
1.672 albertel 2137: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2138: }
2139: }
1.8 www 2140: rename($transname,$filename);
1.607 raeburn 2141: return 'ok';
1.8 www 2142: }
1.290 www 2143: }
1.8 www 2144: }
1.330 www 2145: }
2146:
2147: # ------------------------------------------------ Get server side include body
2148: sub ssi_body {
1.381 albertel 2149: my ($filelink,%form)=@_;
1.606 matthew 2150: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2151: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2152: }
1.953 www 2153: my $output='';
2154: my $response;
1.980 raeburn 2155: if ($filelink=~/^https?\:/) {
1.954 raeburn 2156: ($output,$response)=&externalssi($filelink);
1.953 www 2157: } else {
1.1004 droeschl 2158: $filelink .= $filelink=~/\?/ ? '&' : '?';
2159: $filelink .= 'inhibitmenu=yes';
1.953 www 2160: ($output,$response)=&ssi($filelink,%form);
2161: }
1.778 albertel 2162: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2163: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2164: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2165: if (wantarray) {
2166: return ($output, $response);
2167: } else {
2168: return $output;
2169: }
1.8 www 2170: }
2171:
1.15 www 2172: # --------------------------------------------------------- Server Side Include
2173:
1.782 albertel 2174: sub absolute_url {
2175: my ($host_name) = @_;
2176: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2177: if ($host_name eq '') {
2178: $host_name = $ENV{'SERVER_NAME'};
2179: }
2180: return $protocol.$host_name;
2181: }
2182:
1.942 foxr 2183: #
2184: # Server side include.
2185: # Parameters:
2186: # fn Possibly encrypted resource name/id.
2187: # form Hash that describes how the rendering should be done
2188: # and other things.
1.944 foxr 2189: # Returns:
1.950 raeburn 2190: # Scalar context: The content of the response.
2191: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2192: #
1.15 www 2193: sub ssi {
2194:
1.944 foxr 2195: my ($fn,%form)=@_;
1.15 www 2196: my $ua=new LWP::UserAgent;
1.23 www 2197: my $request;
1.711 albertel 2198:
2199: $form{'no_update_last_known'}=1;
1.895 albertel 2200: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2201: if (%form) {
1.782 albertel 2202: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2203: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2204: } else {
1.782 albertel 2205: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2206: }
2207:
1.15 www 2208: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2209: my $response=$ua->request($request);
2210:
1.944 foxr 2211: if (wantarray) {
2212: return ($response->content, $response);
2213: } else {
2214: return $response->content;
1.942 foxr 2215: }
1.324 www 2216: }
2217:
2218: sub externalssi {
2219: my ($url)=@_;
2220: my $ua=new LWP::UserAgent;
2221: my $request=new HTTP::Request('GET',$url);
2222: my $response=$ua->request($request);
1.954 raeburn 2223: if (wantarray) {
2224: return ($response->content, $response);
2225: } else {
2226: return $response->content;
2227: }
1.15 www 2228: }
1.254 www 2229:
1.492 albertel 2230: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2231:
2232: sub allowuploaded {
2233: my ($srcurl,$url)=@_;
2234: $url=&clutter(&declutter($url));
2235: my $dir=$url;
2236: $dir=~s/\/[^\/]+$//;
2237: my %httpref=();
2238: my $httpurl=&hreflocation('',$url);
2239: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2240: &Apache::lonnet::appenv(\%httpref);
1.254 www 2241: }
1.477 raeburn 2242:
1.478 albertel 2243: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2244: # input: action, courseID, current domain, intended
1.637 raeburn 2245: # path to file, source of file, instruction to parse file for objects,
2246: # ref to hash for embedded objects,
2247: # ref to hash for codebase of java objects.
1.1056.4.16 raeburn 2248: # reference to scalar to accommodate mime type determined
2249: # from File::MMagic if $parser = parse.
1.637 raeburn 2250: #
1.485 raeburn 2251: # output: url to file (if action was uploaddoc),
2252: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2253: #
1.478 albertel 2254: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2255: # course.
1.477 raeburn 2256: #
1.478 albertel 2257: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2258: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2259: # course's home server.
1.477 raeburn 2260: #
1.478 albertel 2261: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2262: # be copied from $source (current location) to
2263: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2264: # and will then be copied to
2265: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2266: # course's home server.
1.485 raeburn 2267: #
1.481 raeburn 2268: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2269: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2270: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2271: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2272: # in course's home server.
1.637 raeburn 2273: #
1.477 raeburn 2274:
2275: sub process_coursefile {
1.1056.4.16 raeburn 2276: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2277: $mimetype)=@_;
1.477 raeburn 2278: my $fetchresult;
1.638 albertel 2279: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2280: if ($action eq 'propagate') {
1.638 albertel 2281: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2282: $home);
1.481 raeburn 2283: } else {
1.477 raeburn 2284: my $fpath = '';
2285: my $fname = $file;
1.478 albertel 2286: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2287: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2288: my $filepath = &build_filepath($fpath);
1.481 raeburn 2289: if ($action eq 'copy') {
2290: if ($source eq '') {
2291: $fetchresult = 'no source file';
2292: return $fetchresult;
2293: } else {
2294: my $destination = $filepath.'/'.$fname;
2295: rename($source,$destination);
2296: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2297: $home);
1.481 raeburn 2298: }
2299: } elsif ($action eq 'uploaddoc') {
2300: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2301: print $fh $env{'form.'.$source};
1.481 raeburn 2302: close($fh);
1.637 raeburn 2303: if ($parser eq 'parse') {
1.1024 raeburn 2304: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2305: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2306: if ($type eq 'text/html') {
1.1024 raeburn 2307: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2308: unless ($parse_result eq 'ok') {
2309: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2310: }
1.637 raeburn 2311: }
1.1056.4.16 raeburn 2312: if (ref($mimetype)) {
2313: $$mimetype = $type;
2314: }
1.637 raeburn 2315: }
1.477 raeburn 2316: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2317: $home);
1.481 raeburn 2318: if ($fetchresult eq 'ok') {
2319: return '/uploaded/'.$fpath.'/'.$fname;
2320: } else {
2321: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2322: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2323: return '/adm/notfound.html';
2324: }
1.477 raeburn 2325: }
2326: }
1.485 raeburn 2327: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2328: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2329: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2330: }
2331: return $fetchresult;
2332: }
2333:
1.637 raeburn 2334: sub build_filepath {
2335: my ($fpath) = @_;
2336: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2337: unless ($fpath eq '') {
2338: my @parts=split('/',$fpath);
2339: foreach my $part (@parts) {
2340: $filepath.= '/'.$part;
2341: if ((-e $filepath)!=1) {
2342: mkdir($filepath,0777);
2343: }
2344: }
2345: }
2346: return $filepath;
2347: }
2348:
2349: sub store_edited_file {
1.638 albertel 2350: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2351: my $file = $primary_url;
2352: $file =~ s#^/uploaded/$docudom/$docuname/##;
2353: my $fpath = '';
2354: my $fname = $file;
2355: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2356: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2357: my $filepath = &build_filepath($fpath);
2358: open(my $fh,'>'.$filepath.'/'.$fname);
2359: print $fh $content;
2360: close($fh);
1.638 albertel 2361: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2362: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2363: $home);
1.637 raeburn 2364: if ($$fetchresult eq 'ok') {
2365: return '/uploaded/'.$fpath.'/'.$fname;
2366: } else {
1.638 albertel 2367: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2368: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2369: return '/adm/notfound.html';
2370: }
2371: }
2372:
1.531 albertel 2373: sub clean_filename {
1.831 albertel 2374: my ($fname,$args)=@_;
1.315 www 2375: # Replace Windows backslashes by forward slashes
1.257 www 2376: $fname=~s/\\/\//g;
1.831 albertel 2377: if (!$args->{'keep_path'}) {
2378: # Get rid of everything but the actual filename
2379: $fname=~s/^.*\/([^\/]+)$/$1/;
2380: }
1.315 www 2381: # Replace spaces by underscores
2382: $fname=~s/\s+/\_/g;
2383: # Replace all other weird characters by nothing
1.831 albertel 2384: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2385: # Replace all .\d. sequences with _\d. so they no longer look like version
2386: # numbers
2387: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2388: return $fname;
2389: }
1.1051 raeburn 2390: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2391: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2392: # image with the same aspect ratio as the original, but with dimensions which do
2393: # not exceed $resizewidth and $resizeheight.
2394:
1.984 neumanie 2395: sub resizeImage {
1.1051 raeburn 2396: my ($img_path,$resizewidth,$resizeheight) = @_;
2397: my $ima = Image::Magick->new;
2398: my $resized;
2399: if (-e $img_path) {
2400: $ima->Read($img_path);
2401: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2402: my $width = $ima->Get('width');
2403: my $height = $ima->Get('height');
2404: if ($width > $resizewidth) {
2405: my $factor = $width/$resizewidth;
2406: my $newheight = $height/$factor;
2407: $ima->Scale(width=>$resizewidth,height=>$newheight);
2408: $resized = 1;
2409: }
2410: }
2411: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2412: my $width = $ima->Get('width');
2413: my $height = $ima->Get('height');
2414: if ($height > $resizeheight) {
2415: my $factor = $height/$resizeheight;
2416: my $newwidth = $width/$factor;
2417: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2418: $resized = 1;
2419: }
2420: }
2421: if ($resized) {
2422: $ima->Write($img_path);
2423: }
2424: }
2425: return;
1.977 amueller 2426: }
2427:
1.608 albertel 2428: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2429: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13 raeburn 2430: # the desired filename is in $env{"form.$formname.filename"}
2431: # $context - possible values: coursedoc, existingfile, overwrite,
2432: # canceloverwrite, or ''.
2433: # if 'coursedoc': upload to the current course
2434: # if 'existingfile': write file to tmp/overwrites directory
2435: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2436: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2437: # $subdir - directory in userfile to store the file into
1.858 raeburn 2438: # $parser - instruction to parse file for objects ($parser = parse)
2439: # $allfiles - reference to hash for embedded objects
2440: # $codebase - reference to hash for codebase of java objects
2441: # $desuname - username for permanent storage of uploaded file
2442: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2443: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2444: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2445: # $resizewidth - width (pixels) to which to resize uploaded image
2446: # $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16 raeburn 2447: # $mimetype - reference to scalar to accommodate mime type determined
2448: # from File::MMagic if $parser = parse.
1.858 raeburn 2449: #
1.686 albertel 2450: # output: url of file in userspace, or error: <message>
2451: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2452:
1.531 albertel 2453: sub userfileupload {
1.1056.4.13 raeburn 2454: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16 raeburn 2455: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2456: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2457: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2458: $fname=&clean_filename($fname);
1.1056.4.13 raeburn 2459: # See if there is anything left
1.257 www 2460: unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13 raeburn 2461: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2462: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2463: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2464: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2465: my $now = time;
1.1056.4.13 raeburn 2466: my $filepath;
2467: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2468: $filepath = 'tmp/helprequests/'.$now;
2469: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2470: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2471: '_'.$env{'user.domain'}.'/pending';
2472: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2473: my ($docuname,$docudom);
2474: if ($destudom) {
2475: $docudom = $destudom;
2476: } else {
2477: $docudom = $env{'user.domain'};
2478: }
2479: if ($destuname) {
2480: $docuname = $destuname;
2481: } else {
2482: $docuname = $env{'user.name'};
2483: }
2484: if (exists($env{'form.group'})) {
2485: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2486: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2487: }
2488: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2489: if ($context eq 'canceloverwrite') {
2490: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2491: if (-e $tempfile) {
2492: my @info = stat($tempfile);
2493: if ($info[9] eq $env{'form.timestamp'}) {
2494: unlink($tempfile);
2495: }
2496: }
2497: return;
1.523 raeburn 2498: }
2499: }
1.1056.4.13 raeburn 2500: # Create the directory if not present
1.741 raeburn 2501: my @parts=split(/\//,$filepath);
2502: my $fullpath = $perlvar{'lonDaemons'};
2503: for (my $i=0;$i<@parts;$i++) {
2504: $fullpath .= '/'.$parts[$i];
2505: if ((-e $fullpath)!=1) {
2506: mkdir($fullpath,0777);
2507: }
2508: }
2509: open(my $fh,'>'.$fullpath.'/'.$fname);
2510: print $fh $env{'form.'.$formname};
2511: close($fh);
1.1056.4.13 raeburn 2512: if ($context eq 'existingfile') {
2513: my @info = stat($fullpath.'/'.$fname);
2514: return ($fullpath.'/'.$fname,$info[9]);
2515: } else {
2516: return $fullpath.'/'.$fname;
2517: }
1.523 raeburn 2518: }
1.995 raeburn 2519: if ($subdir eq 'scantron') {
2520: $fname = 'scantron_orig_'.$fname;
1.1056.4.14 raeburn 2521: } else {
1.995 raeburn 2522: $fname="$subdir/$fname";
2523: }
1.1056.4.13 raeburn 2524: if ($context eq 'coursedoc') {
1.638 albertel 2525: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2526: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2527: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2528: return &finishuserfileupload($docuname,$docudom,
2529: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2530: $codebase,$thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2531: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2532: } else {
1.620 albertel 2533: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2534: return &process_coursefile('uploaddoc',$docuname,$docudom,
2535: $fname,$formname,$parser,
1.1056.4.16 raeburn 2536: $allfiles,$codebase,$mimetype);
1.481 raeburn 2537: }
1.719 banghart 2538: } elsif (defined($destuname)) {
2539: my $docuname=$destuname;
2540: my $docudom=$destudom;
1.860 raeburn 2541: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2542: $parser,$allfiles,$codebase,
1.1051 raeburn 2543: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2544: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2545: } else {
1.638 albertel 2546: my $docuname=$env{'user.name'};
2547: my $docudom=$env{'user.domain'};
1.714 raeburn 2548: if (exists($env{'form.group'})) {
2549: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2550: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2551: }
1.860 raeburn 2552: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2553: $parser,$allfiles,$codebase,
1.1051 raeburn 2554: $thumbwidth,$thumbheight,
1.1056.4.16 raeburn 2555: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2556: }
1.271 www 2557: }
2558:
2559: sub finishuserfileupload {
1.860 raeburn 2560: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16 raeburn 2561: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2562: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2563: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2564:
1.860 raeburn 2565: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2566: $file=$fname;
2567: if ($fname=~m|/|) {
2568: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2569: $path.=$fnamepath.'/';
2570: }
1.259 www 2571: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2572: my $count;
2573: for ($count=4;$count<=$#parts;$count++) {
2574: $filepath.="/$parts[$count]";
2575: if ((-e $filepath)!=1) {
2576: mkdir($filepath,0777);
2577: }
2578: }
1.984 neumanie 2579:
1.258 www 2580: # Save the file
2581: {
1.701 albertel 2582: if (!open(FH,'>'.$filepath.'/'.$file)) {
2583: &logthis('Failed to create '.$filepath.'/'.$file);
2584: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2585: return '/adm/notfound.html';
2586: }
1.1056.4.13 raeburn 2587: if ($context eq 'overwrite') {
2588: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2589: my $target = $filepath.'/'.$file;
2590: if (-e $source) {
2591: my @info = stat($source);
2592: if ($info[9] eq $env{'form.timestamp'}) {
2593: unless (&File::Copy::move($source,$target)) {
2594: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2595: return "Moving from $source failed";
2596: }
2597: } else {
2598: return "Temporary file: $source had unexpected date/time for last modification";
2599: }
2600: } else {
2601: return "Temporary file: $source missing";
2602: }
2603: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2604: &logthis('Failed to write to '.$filepath.'/'.$file);
2605: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2606: return '/adm/notfound.html';
2607: }
1.570 albertel 2608: close(FH);
1.1051 raeburn 2609: if ($resizewidth && $resizeheight) {
2610: my $mm = new File::MMagic;
2611: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2612: if ($mime_type =~ m{^image/}) {
2613: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2614: }
1.977 amueller 2615: }
1.258 www 2616: }
1.637 raeburn 2617: if ($parser eq 'parse') {
1.1024 raeburn 2618: my $mm = new File::MMagic;
1.1056.4.16 raeburn 2619: my $type = $mm->checktype_filename($filepath.'/'.$file);
2620: if ($type eq 'text/html') {
1.1024 raeburn 2621: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2622: $allfiles,$codebase);
2623: unless ($parse_result eq 'ok') {
2624: &logthis('Failed to parse '.$filepath.$file.
2625: ' for embedded media: '.$parse_result);
2626: }
1.637 raeburn 2627: }
1.1056.4.16 raeburn 2628: if (ref($mimetype)) {
2629: $$mimetype = $type;
2630: }
1.637 raeburn 2631: }
1.860 raeburn 2632: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2633: my $input = $filepath.'/'.$file;
2634: my $output = $filepath.'/'.'tn-'.$file;
2635: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2636: system("convert -sample $thumbsize $input $output");
2637: if (-e $filepath.'/'.'tn-'.$file) {
2638: $fetchthumb = 1;
2639: }
2640: }
1.858 raeburn 2641:
1.259 www 2642: # Notify homeserver to grep it
2643: #
1.984 neumanie 2644: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2645: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2646: if ($fetchresult eq 'ok') {
1.860 raeburn 2647: if ($fetchthumb) {
2648: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2649: if ($thumbresult ne 'ok') {
2650: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2651: $docuhome.': '.$thumbresult);
2652: }
2653: }
1.259 www 2654: #
1.258 www 2655: # Return the URL to it
1.494 albertel 2656: return '/uploaded/'.$path.$file;
1.263 www 2657: } else {
1.494 albertel 2658: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2659: ': '.$fetchresult);
1.263 www 2660: return '/adm/notfound.html';
1.858 raeburn 2661: }
1.493 albertel 2662: }
2663:
1.637 raeburn 2664: sub extract_embedded_items {
1.961 raeburn 2665: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2666: my @state = ();
2667: my %javafiles = (
2668: codebase => '',
2669: code => '',
2670: archive => ''
2671: );
2672: my %mediafiles = (
2673: src => '',
2674: movie => '',
2675: );
1.648 raeburn 2676: my $p;
2677: if ($content) {
2678: $p = HTML::LCParser->new($content);
2679: } else {
1.961 raeburn 2680: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2681: }
1.641 albertel 2682: while (my $t=$p->get_token()) {
1.640 albertel 2683: if ($t->[0] eq 'S') {
2684: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2685: push(@state, $tagname);
1.648 raeburn 2686: if (lc($tagname) eq 'allow') {
2687: &add_filetype($allfiles,$attr->{'src'},'src');
2688: }
1.640 albertel 2689: if (lc($tagname) eq 'img') {
2690: &add_filetype($allfiles,$attr->{'src'},'src');
2691: }
1.886 albertel 2692: if (lc($tagname) eq 'a') {
2693: &add_filetype($allfiles,$attr->{'href'},'href');
2694: }
1.645 raeburn 2695: if (lc($tagname) eq 'script') {
2696: if ($attr->{'archive'} =~ /\.jar$/i) {
2697: &add_filetype($allfiles,$attr->{'archive'},'archive');
2698: } else {
2699: &add_filetype($allfiles,$attr->{'src'},'src');
2700: }
2701: }
2702: if (lc($tagname) eq 'link') {
2703: if (lc($attr->{'rel'}) eq 'stylesheet') {
2704: &add_filetype($allfiles,$attr->{'href'},'href');
2705: }
2706: }
1.640 albertel 2707: if (lc($tagname) eq 'object' ||
2708: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2709: foreach my $item (keys(%javafiles)) {
2710: $javafiles{$item} = '';
2711: }
2712: }
2713: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2714: my $name = lc($attr->{'name'});
2715: foreach my $item (keys(%javafiles)) {
2716: if ($name eq $item) {
2717: $javafiles{$item} = $attr->{'value'};
2718: last;
2719: }
2720: }
2721: foreach my $item (keys(%mediafiles)) {
2722: if ($name eq $item) {
2723: &add_filetype($allfiles, $attr->{'value'}, 'value');
2724: last;
2725: }
2726: }
2727: }
2728: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2729: foreach my $item (keys(%javafiles)) {
2730: if ($attr->{$item}) {
2731: $javafiles{$item} = $attr->{$item};
2732: last;
2733: }
2734: }
2735: foreach my $item (keys(%mediafiles)) {
2736: if ($attr->{$item}) {
2737: &add_filetype($allfiles,$attr->{$item},$item);
2738: last;
2739: }
2740: }
2741: }
2742: } elsif ($t->[0] eq 'E') {
2743: my ($tagname) = ($t->[1]);
2744: if ($javafiles{'codebase'} ne '') {
2745: $javafiles{'codebase'} .= '/';
2746: }
2747: if (lc($tagname) eq 'applet' ||
2748: lc($tagname) eq 'object' ||
2749: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2750: ) {
2751: foreach my $item (keys(%javafiles)) {
2752: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2753: my $file=$javafiles{'codebase'}.$javafiles{$item};
2754: &add_filetype($allfiles,$file,$item);
2755: }
2756: }
2757: }
2758: pop @state;
2759: }
2760: }
1.637 raeburn 2761: return 'ok';
2762: }
2763:
1.639 albertel 2764: sub add_filetype {
2765: my ($allfiles,$file,$type)=@_;
2766: if (exists($allfiles->{$file})) {
2767: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2768: push(@{$allfiles->{$file}}, &escape($type));
2769: }
2770: } else {
2771: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2772: }
2773: }
2774:
1.493 albertel 2775: sub removeuploadedurl {
1.984 neumanie 2776: my ($url)=@_;
2777: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2778: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2779: }
2780:
2781: sub removeuserfile {
2782: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2783: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2784: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2785: if ($result eq 'ok') {
1.798 raeburn 2786: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2787: my $metafile = $fname.'.meta';
2788: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2789: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2790: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2791: my $sqlresult =
1.823 albertel 2792: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2793: 'portfolio_metadata',$group,
2794: 'delete');
1.798 raeburn 2795: }
2796: }
2797: return $result;
1.257 www 2798: }
1.15 www 2799:
1.530 albertel 2800: sub mkdiruserfile {
2801: my ($docuname,$docudom,$dir)=@_;
2802: my $home=&homeserver($docuname,$docudom);
2803: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2804: }
2805:
1.531 albertel 2806: sub renameuserfile {
2807: my ($docuname,$docudom,$old,$new)=@_;
2808: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2809: my $result = &reply("renameuserfile:$docudom:$docuname:".
2810: &escape("$old").':'.&escape("$new"),$home);
2811: if ($result eq 'ok') {
2812: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2813: my $oldmeta = $old.'.meta';
2814: my $newmeta = $new.'.meta';
2815: my $metaresult =
2816: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2817: my $url = "/uploaded/$docudom/$docuname/$old";
2818: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2819: my $sqlresult =
1.823 albertel 2820: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2821: 'portfolio_metadata',$group,
2822: 'delete');
1.798 raeburn 2823: }
2824: }
2825: return $result;
1.531 albertel 2826: }
2827:
1.14 www 2828: # ------------------------------------------------------------------------- Log
2829:
2830: sub log {
2831: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2832: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2833: }
2834:
2835: # ------------------------------------------------------------------ Course Log
1.352 www 2836: #
2837: # This routine flushes several buffers of non-mission-critical nature
2838: #
1.157 www 2839:
2840: sub flushcourselogs {
1.352 www 2841: &logthis('Flushing log buffers');
2842: #
2843: # course logs
2844: # This is a log of all transactions in a course, which can be used
2845: # for data mining purposes
2846: #
2847: # It also collects the courseid database, which lists last transaction
2848: # times and course titles for all courseids
2849: #
2850: my %courseidbuffer=();
1.921 raeburn 2851: foreach my $crsid (keys(%courselogs)) {
1.352 www 2852: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2853: &escape($courselogs{$crsid}),
2854: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2855: delete $courselogs{$crsid};
2856: } else {
2857: &logthis('Failed to flush log buffer for '.$crsid);
2858: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2859: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2860: " exceeded maximum size, deleting.</font>");
2861: delete $courselogs{$crsid};
2862: }
1.352 www 2863: }
1.920 raeburn 2864: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2865: 'description' => $coursedescrbuf{$crsid},
2866: 'inst_code' => $courseinstcodebuf{$crsid},
2867: 'type' => $coursetypebuf{$crsid},
2868: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2869: };
1.191 harris41 2870: }
1.352 www 2871: #
2872: # Write course id database (reverse lookup) to homeserver of courses
2873: # Is used in pickcourse
2874: #
1.840 albertel 2875: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2876: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2877: $courseidbuffer{$crs_home},
2878: $crs_home,'timeonly');
1.352 www 2879: }
2880: #
2881: # File accesses
2882: # Writes to the dynamic metadata of resources to get hit counts, etc.
2883: #
1.449 matthew 2884: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2885: if ($entry =~ /___count$/) {
2886: my ($dom,$name);
1.807 albertel 2887: ($dom,$name,undef)=
1.811 albertel 2888: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2889: if (! defined($dom) || $dom eq '' ||
2890: ! defined($name) || $name eq '') {
1.620 albertel 2891: my $cid = $env{'request.course.id'};
2892: $dom = $env{'request.'.$cid.'.domain'};
2893: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2894: }
1.450 matthew 2895: my $value = $accesshash{$entry};
2896: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2897: my %temphash=($url => $value);
1.449 matthew 2898: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2899: if ($result eq 'ok') {
2900: delete $accesshash{$entry};
2901: } elsif ($result eq 'unknown_cmd') {
2902: # Target server has old code running on it.
1.450 matthew 2903: my %temphash=($entry => $value);
1.449 matthew 2904: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2905: delete $accesshash{$entry};
2906: }
2907: }
2908: } else {
1.811 albertel 2909: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2910: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2911: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2912: delete $accesshash{$entry};
2913: }
1.185 www 2914: }
1.191 harris41 2915: }
1.352 www 2916: #
2917: # Roles
2918: # Reverse lookup of user roles for course faculty/staff and co-authorship
2919: #
1.800 albertel 2920: foreach my $entry (keys(%userrolehash)) {
1.351 www 2921: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2922: split(/\:/,$entry);
2923: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2924: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2925: $rudom,$runame) eq 'ok') {
2926: delete $userrolehash{$entry};
2927: }
2928: }
1.662 raeburn 2929: #
2930: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2931: #
2932: my %domrolebuffer = ();
1.1000 raeburn 2933: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2934: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2935: if ($domrolebuffer{$rudom}) {
2936: $domrolebuffer{$rudom}.='&'.&escape($entry).
2937: '='.&escape($domainrolehash{$entry});
2938: } else {
2939: $domrolebuffer{$rudom}.=&escape($entry).
2940: '='.&escape($domainrolehash{$entry});
2941: }
2942: delete $domainrolehash{$entry};
2943: }
2944: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2945: my %servers = &get_servers($dom,'library');
2946: foreach my $tryserver (keys(%servers)) {
2947: unless (&reply('domroleput:'.$dom.':'.
2948: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2949: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2950: }
1.662 raeburn 2951: }
2952: }
1.186 www 2953: $dumpcount++;
1.157 www 2954: }
2955:
2956: sub courselog {
2957: my $what=shift;
1.158 www 2958: $what=time.':'.$what;
1.620 albertel 2959: unless ($env{'request.course.id'}) { return ''; }
2960: $coursedombuf{$env{'request.course.id'}}=
2961: $env{'course.'.$env{'request.course.id'}.'.domain'};
2962: $coursenumbuf{$env{'request.course.id'}}=
2963: $env{'course.'.$env{'request.course.id'}.'.num'};
2964: $coursehombuf{$env{'request.course.id'}}=
2965: $env{'course.'.$env{'request.course.id'}.'.home'};
2966: $coursedescrbuf{$env{'request.course.id'}}=
2967: $env{'course.'.$env{'request.course.id'}.'.description'};
2968: $courseinstcodebuf{$env{'request.course.id'}}=
2969: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2970: $courseownerbuf{$env{'request.course.id'}}=
2971: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2972: $coursetypebuf{$env{'request.course.id'}}=
2973: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2974: if (defined $courselogs{$env{'request.course.id'}}) {
2975: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2976: } else {
1.620 albertel 2977: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2978: }
1.620 albertel 2979: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2980: &flushcourselogs();
2981: }
1.158 www 2982: }
2983:
2984: sub courseacclog {
2985: my $fnsymb=shift;
1.620 albertel 2986: unless ($env{'request.course.id'}) { return ''; }
2987: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2988: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2989: $what.=':POST';
1.583 matthew 2990: # FIXME: Probably ought to escape things....
1.800 albertel 2991: foreach my $key (keys(%env)) {
2992: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2993: my $formitem = $1;
2994: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2995: $what.=':'.$formitem.'='.$env{$key};
2996: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2997: $what.=':'.$formitem.'='.$env{$key};
2998: }
1.158 www 2999: }
1.191 harris41 3000: }
1.583 matthew 3001: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3002: # FIXME: We should not be depending on a form parameter that someone
3003: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3004: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3005: $what.= ':POST';
3006: # FIXME: Probably ought to escape things....
3007: foreach my $element ('courseexp','crsfulltext','crsrelated',
3008: 'crsdiscuss') {
1.620 albertel 3009: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3010: }
3011: }
1.158 www 3012: }
3013: &courselog($what);
1.149 www 3014: }
3015:
1.185 www 3016: sub countacc {
3017: my $url=&declutter(shift);
1.458 matthew 3018: return if (! defined($url) || $url eq '');
1.620 albertel 3019: unless ($env{'request.course.id'}) { return ''; }
3020: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3021: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3022: $accesshash{$key}++;
1.185 www 3023: }
1.349 www 3024:
1.361 www 3025: sub linklog {
3026: my ($from,$to)=@_;
3027: $from=&declutter($from);
3028: $to=&declutter($to);
3029: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3030: $accesshash{$to.'___'.$from.'___goto'}=1;
3031: }
3032:
1.349 www 3033: sub userrolelog {
3034: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3035: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3036: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3037: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3038: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3039: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3040: $userrolehash
3041: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3042: =$tend.':'.$tstart;
1.662 raeburn 3043: }
1.898 albertel 3044: if (($env{'request.role'} =~ /dc\./) &&
3045: (($trole=~/^au/) || ($trole=~/^in/) ||
3046: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3047: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3048: ($trole=~/^co/))) {
1.898 albertel 3049: $userrolehash
3050: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3051: =$tend.':'.$tstart;
3052: }
1.662 raeburn 3053: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3054: ($trole=~/^li/) || ($trole=~/^li/) ||
3055: ($trole=~/^au/) || ($trole=~/^dg/) ||
3056: ($trole=~/^sc/)) {
3057: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3058: $domainrolehash
3059: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3060: = $tend.':'.$tstart;
3061: }
1.351 www 3062: }
3063:
1.957 raeburn 3064: sub courserolelog {
3065: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3066: if (($trole eq 'cc') || ($trole eq 'in') ||
3067: ($trole eq 'ep') || ($trole eq 'ad') ||
3068: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3069: ($trole=~/^cr/) || ($trole eq 'gr') ||
3070: ($trole eq 'co')) {
1.957 raeburn 3071: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3072: my $cdom = $1;
3073: my $cnum = $2;
3074: my $sec = $3;
3075: my $namespace = 'rolelog';
3076: my %storehash = (
3077: role => $trole,
3078: start => $tstart,
3079: end => $tend,
3080: selfenroll => $selfenroll,
3081: context => $context,
3082: );
3083: if ($trole eq 'gr') {
3084: $namespace = 'groupslog';
3085: $storehash{'group'} = $sec;
3086: } else {
3087: $storehash{'section'} = $sec;
3088: }
3089: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3090: if (($trole ne 'st') || ($sec ne '')) {
3091: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3092: }
1.957 raeburn 3093: }
3094: }
3095: return;
3096: }
3097:
1.351 www 3098: sub get_course_adv_roles {
1.948 raeburn 3099: my ($cid,$codes) = @_;
1.620 albertel 3100: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3101: my %coursehash=&coursedescription($cid);
1.988 raeburn 3102: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3103: my %nothide=();
1.800 albertel 3104: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3105: if ($user !~ /:/) {
3106: $nothide{join(':',split(/[\@]/,$user))}=1;
3107: } else {
3108: $nothide{$user}=1;
3109: }
1.470 www 3110: }
1.351 www 3111: my %returnhash=();
3112: my %dumphash=
3113: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3114: my $now=time;
1.997 raeburn 3115: my %privileged;
1.1000 raeburn 3116: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3117: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3118: if (($tstart) && ($tstart<0)) { next; }
3119: if (($tend) && ($tend<$now)) { next; }
3120: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3121: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3122: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3123: unless (ref($privileged{$domain}) eq 'HASH') {
3124: my %dompersonnel =
1.998 raeburn 3125: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3126: $privileged{$domain} = {};
3127: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3128: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3129: foreach my $user (keys(%{$dompersonnel{$server}})) {
3130: my ($trole,$uname,$udom) = split(/:/,$user);
3131: $privileged{$udom}{$uname} = 1;
3132: }
3133: }
3134: }
3135: }
3136: if ((exists($privileged{$domain}{$username})) &&
3137: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3138: if ($role eq 'cr') { next; }
1.948 raeburn 3139: if ($codes) {
3140: if ($section) { $role .= ':'.$section; }
3141: if ($returnhash{$role}) {
3142: $returnhash{$role}.=','.$username.':'.$domain;
3143: } else {
3144: $returnhash{$role}=$username.':'.$domain;
3145: }
1.351 www 3146: } else {
1.988 raeburn 3147: my $key=&plaintext($role,$crstype);
1.973 bisitz 3148: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3149: if ($returnhash{$key}) {
3150: $returnhash{$key}.=','.$username.':'.$domain;
3151: } else {
3152: $returnhash{$key}=$username.':'.$domain;
3153: }
1.351 www 3154: }
1.948 raeburn 3155: }
1.400 www 3156: return %returnhash;
3157: }
3158:
3159: sub get_my_roles {
1.937 raeburn 3160: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3161: unless (defined($uname)) { $uname=$env{'user.name'}; }
3162: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3163: my (%dumphash,%nothide);
1.858 raeburn 3164: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3165: my $extra = &freeze_escape({'skipcheck' => 1});
3166: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3167: } else {
3168: %dumphash=
1.400 www 3169: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3170: if ($hidepriv) {
3171: my %coursehash=&coursedescription($udom.'_'.$uname);
3172: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3173: if ($user !~ /:/) {
3174: $nothide{join(':',split(/[\@]/,$user))} = 1;
3175: } else {
3176: $nothide{$user} = 1;
3177: }
3178: }
3179: }
1.858 raeburn 3180: }
1.400 www 3181: my %returnhash=();
3182: my $now=time;
1.999 raeburn 3183: my %privileged;
1.800 albertel 3184: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3185: my ($role,$tend,$tstart);
3186: if ($context eq 'userroles') {
3187: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3188: } else {
3189: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3190: }
1.400 www 3191: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3192: my $status = 'active';
1.939 raeburn 3193: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3194: $status = 'previous';
3195: }
3196: if (($tstart) && ($now<$tstart)) {
3197: $status = 'future';
3198: }
3199: if (ref($types) eq 'ARRAY') {
3200: if (!grep(/^\Q$status\E$/,@{$types})) {
3201: next;
3202: }
3203: } else {
3204: if ($status ne 'active') {
3205: next;
3206: }
3207: }
1.867 raeburn 3208: my ($rolecode,$username,$domain,$section,$area);
3209: if ($context eq 'userroles') {
3210: ($area,$rolecode) = split(/_/,$entry);
3211: (undef,$domain,$username,$section) = split(/\//,$area);
3212: } else {
3213: ($role,$username,$domain,$section) = split(/\:/,$entry);
3214: }
1.832 raeburn 3215: if (ref($roledoms) eq 'ARRAY') {
3216: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3217: next;
3218: }
3219: }
3220: if (ref($roles) eq 'ARRAY') {
3221: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3222: if ($role =~ /^cr\//) {
3223: if (!grep(/^cr$/,@{$roles})) {
3224: next;
3225: }
3226: } else {
3227: next;
3228: }
1.832 raeburn 3229: }
1.867 raeburn 3230: }
1.937 raeburn 3231: if ($hidepriv) {
1.999 raeburn 3232: if ($context eq 'userroles') {
3233: if ((&privileged($username,$domain)) &&
3234: (!$nothide{$username.':'.$domain})) {
3235: next;
3236: }
3237: } else {
3238: unless (ref($privileged{$domain}) eq 'HASH') {
3239: my %dompersonnel =
3240: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3241: $privileged{$domain} = {};
3242: if (keys(%dompersonnel)) {
3243: foreach my $server (keys(%dompersonnel)) {
3244: if (ref($dompersonnel{$server}) eq 'HASH') {
3245: foreach my $user (keys(%{$dompersonnel{$server}})) {
3246: my ($trole,$uname,$udom) = split(/:/,$user);
3247: $privileged{$udom}{$uname} = $trole;
3248: }
3249: }
3250: }
3251: }
3252: }
3253: if (exists($privileged{$domain}{$username})) {
3254: if (!$nothide{$username.':'.$domain}) {
3255: next;
3256: }
3257: }
1.937 raeburn 3258: }
3259: }
1.933 raeburn 3260: if ($withsec) {
3261: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3262: $tstart.':'.$tend;
3263: } else {
3264: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3265: }
1.832 raeburn 3266: }
1.373 www 3267: return %returnhash;
1.399 www 3268: }
3269:
3270: # ----------------------------------------------------- Frontpage Announcements
3271: #
3272: #
3273:
3274: sub postannounce {
3275: my ($server,$text)=@_;
1.844 albertel 3276: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3277: unless ($text=~/\w/) { $text=''; }
3278: return &reply('setannounce:'.&escape($text),$server);
3279: }
3280:
3281: sub getannounce {
1.448 albertel 3282:
3283: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3284: my $announcement='';
1.800 albertel 3285: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3286: close($fh);
1.399 www 3287: if ($announcement=~/\w/) {
3288: return
3289: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3290: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3291: } else {
3292: return '';
3293: }
3294: } else {
3295: return '';
3296: }
1.351 www 3297: }
1.353 www 3298:
3299: # ---------------------------------------------------------- Course ID routines
3300: # Deal with domain's nohist_courseid.db files
3301: #
3302:
3303: sub courseidput {
1.921 raeburn 3304: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3305: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3306: my $outcome;
3307: if ($caller eq 'timeonly') {
3308: my $cids = '';
3309: foreach my $item (keys(%$storehash)) {
3310: $cids.=&escape($item).'&';
3311: }
3312: $cids=~s/\&$//;
3313: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3314: $coursehome);
3315: } else {
3316: my $items = '';
3317: foreach my $item (keys(%$storehash)) {
3318: $items.= &escape($item).'='.
3319: &freeze_escape($$storehash{$item}).'&';
3320: }
3321: $items=~s/\&$//;
3322: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3323: $coursehome);
1.918 raeburn 3324: }
3325: if ($outcome eq 'unknown_cmd') {
3326: my $what;
3327: foreach my $cid (keys(%$storehash)) {
3328: $what .= &escape($cid).'=';
1.921 raeburn 3329: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3330: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3331: }
3332: $what =~ s/\:$/&/;
3333: }
3334: $what =~ s/\&$//;
3335: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3336: } else {
3337: return $outcome;
3338: }
1.353 www 3339: }
3340:
3341: sub courseiddump {
1.921 raeburn 3342: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3343: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3344: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3345: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3346: my $as_hash = 1;
3347: my %returnhash;
3348: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3349: my %libserv = &all_library();
3350: foreach my $tryserver (keys(%libserv)) {
3351: if ( ( $hostidflag == 1
3352: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3353: || (!defined($hostidflag)) ) {
3354:
1.918 raeburn 3355: if (($domfilter eq '') ||
3356: (&host_domain($tryserver) eq $domfilter)) {
3357: my $rep =
3358: &reply('courseiddump:'.&host_domain($tryserver).':'.
3359: $sincefilter.':'.&escape($descfilter).':'.
3360: &escape($instcodefilter).':'.&escape($ownerfilter).
3361: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3362: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3363: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3364: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3365: &escape($cc_clone).':'.$cloneonly.':'.
3366: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3367: &escape($creationcontext).':'.$domcloner,
3368: $tryserver);
1.918 raeburn 3369: my @pairs=split(/\&/,$rep);
3370: foreach my $item (@pairs) {
3371: my ($key,$value)=split(/\=/,$item,2);
3372: $key = &unescape($key);
3373: next if ($key =~ /^error: 2 /);
3374: my $result = &thaw_unescape($value);
3375: if (ref($result) eq 'HASH') {
3376: $returnhash{$key}=$result;
3377: } else {
1.921 raeburn 3378: my @responses = split(/:/,$value);
3379: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3380: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3381: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3382: }
1.1008 raeburn 3383: }
1.353 www 3384: }
3385: }
3386: }
3387: }
3388: return %returnhash;
3389: }
3390:
1.1055 raeburn 3391: sub courselastaccess {
3392: my ($cdom,$cnum,$hostidref) = @_;
3393: my %returnhash;
3394: if ($cdom && $cnum) {
3395: my $chome = &homeserver($cnum,$cdom);
3396: if ($chome ne 'no_host') {
3397: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3398: &extract_lastaccess(\%returnhash,$rep);
3399: }
3400: } else {
3401: if (!$cdom) { $cdom=''; }
3402: my %libserv = &all_library();
3403: foreach my $tryserver (keys(%libserv)) {
3404: if (ref($hostidref) eq 'ARRAY') {
3405: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3406: }
3407: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3408: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3409: &extract_lastaccess(\%returnhash,$rep);
3410: }
3411: }
3412: }
3413: return %returnhash;
3414: }
3415:
3416: sub extract_lastaccess {
3417: my ($returnhash,$rep) = @_;
3418: if (ref($returnhash) eq 'HASH') {
3419: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3420: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3421: $rep eq '') {
3422: my @pairs=split(/\&/,$rep);
3423: foreach my $item (@pairs) {
3424: my ($key,$value)=split(/\=/,$item,2);
3425: $key = &unescape($key);
3426: next if ($key =~ /^error: 2 /);
3427: $returnhash->{$key} = &thaw_unescape($value);
3428: }
3429: }
3430: }
3431: return;
3432: }
3433:
1.658 raeburn 3434: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3435:
3436: sub dcmailput {
1.685 raeburn 3437: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3438: my $status = &Apache::lonnet::critical(
1.740 www 3439: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3440: &escape($message),$server);
1.662 raeburn 3441: return $status;
3442: }
3443:
1.658 raeburn 3444: sub dcmaildump {
3445: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3446: my %returnhash=();
1.846 albertel 3447:
3448: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3449: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3450: &escape($enddate).':';
3451: my @esc_senders=map { &escape($_)} @$senders;
3452: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3453: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3454: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3455: if (($key) && ($value)) {
3456: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3457: }
3458: }
3459: }
3460: return %returnhash;
3461: }
1.662 raeburn 3462: # ---------------------------------------------------------- Domain roles
3463:
3464: sub get_domain_roles {
3465: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3466: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3467: $startdate = '.';
3468: }
1.1018 raeburn 3469: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3470: $enddate = '.';
3471: }
1.922 raeburn 3472: my $rolelist;
3473: if (ref($roles) eq 'ARRAY') {
3474: $rolelist = join(':',@{$roles});
3475: }
1.662 raeburn 3476: my %personnel = ();
1.841 albertel 3477:
3478: my %servers = &get_servers($dom,'library');
3479: foreach my $tryserver (keys(%servers)) {
3480: %{$personnel{$tryserver}}=();
3481: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3482: &escape($startdate).':'.
3483: &escape($enddate).':'.
3484: &escape($rolelist), $tryserver))) {
3485: my ($key,$value) = split(/\=/,$line,2);
3486: if (($key) && ($value)) {
3487: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3488: }
3489: }
1.662 raeburn 3490: }
3491: return %personnel;
3492: }
1.658 raeburn 3493:
1.149 www 3494: # ----------------------------------------------------------- Check out an item
3495:
1.504 albertel 3496: sub get_first_access {
3497: my ($type,$argsymb)=@_;
1.790 albertel 3498: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3499: if ($argsymb) { $symb=$argsymb; }
3500: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3501: if ($type eq 'course') {
3502: $res='course';
3503: } elsif ($type eq 'map') {
1.588 albertel 3504: $res=&symbread($map);
3505: } else {
3506: $res=$symb;
3507: }
3508: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3509: return $times{"$courseid\0$res"};
1.504 albertel 3510: }
3511:
3512: sub set_first_access {
3513: my ($type)=@_;
1.790 albertel 3514: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3515: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3516: if ($type eq 'course') {
3517: $res='course';
3518: } elsif ($type eq 'map') {
1.588 albertel 3519: $res=&symbread($map);
3520: } else {
3521: $res=$symb;
3522: }
3523: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3524: if (!$firstaccess) {
1.588 albertel 3525: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3526: }
3527: return 'already_set';
1.504 albertel 3528: }
3529:
1.149 www 3530: sub checkout {
3531: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3532: my $now=time;
3533: my $lonhost=$perlvar{'lonHostID'};
3534: my $infostr=&escape(
1.234 www 3535: 'CHECKOUTTOKEN&'.
1.149 www 3536: $tuname.'&'.
3537: $tudom.'&'.
3538: $tcrsid.'&'.
3539: $symb.'&'.
3540: $now.'&'.$ENV{'REMOTE_ADDR'});
3541: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3542: if ($token=~/^error\:/) {
1.672 albertel 3543: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3544: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3545: "</font>");
3546: return '';
3547: }
3548:
1.149 www 3549: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3550: $token=~tr/a-z/A-Z/;
3551:
1.153 www 3552: my %infohash=('resource.0.outtoken' => $token,
3553: 'resource.0.checkouttime' => $now,
3554: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3555:
3556: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3557: return '';
1.151 www 3558: } else {
1.672 albertel 3559: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3560: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3561: "</font>");
1.149 www 3562: }
3563:
3564: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3565: &escape('Checkout '.$infostr.' - '.
3566: $token)) ne 'ok') {
3567: return '';
1.151 www 3568: } else {
1.672 albertel 3569: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3570: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3571: "</font>");
1.149 www 3572: }
1.151 www 3573: return $token;
1.149 www 3574: }
3575:
3576: # ------------------------------------------------------------ Check in an item
3577:
3578: sub checkin {
3579: my $token=shift;
1.150 www 3580: my $now=time;
3581: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3582: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3583: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3584: $dtoken=~s/\W/\_/g;
1.234 www 3585: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3586: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3587:
1.154 www 3588: unless (($tuname) && ($tudom)) {
3589: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3590: return '';
3591: }
3592:
3593: unless (&allowed('mgr',$tcrsid)) {
3594: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3595: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3596: return '';
3597: }
3598:
1.153 www 3599: my %infohash=('resource.0.intoken' => $token,
3600: 'resource.0.checkintime' => $now,
3601: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3602:
3603: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3604: return '';
3605: }
3606:
3607: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3608: &escape('Checkin - '.$token)) ne 'ok') {
3609: return '';
3610: }
3611:
3612: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3613: }
3614:
3615: # --------------------------------------------- Set Expire Date for Spreadsheet
3616:
3617: sub expirespread {
3618: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3619: my $cid=$env{'request.course.id'};
1.110 www 3620: if ($cid) {
3621: my $now=time;
3622: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3623: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3624: $env{'course.'.$cid.'.num'}.
1.110 www 3625: ':nohist_expirationdates:'.
3626: &escape($key).'='.$now,
1.620 albertel 3627: $env{'course.'.$cid.'.home'})
1.110 www 3628: }
3629: return 'ok';
1.14 www 3630: }
3631:
1.109 www 3632: # ----------------------------------------------------- Devalidate Spreadsheets
3633:
3634: sub devalidate {
1.325 www 3635: my ($symb,$uname,$udom)=@_;
1.620 albertel 3636: my $cid=$env{'request.course.id'};
1.109 www 3637: if ($cid) {
1.391 matthew 3638: # delete the stored spreadsheets for
3639: # - the student level sheet of this user in course's homespace
3640: # - the assessment level sheet for this resource
3641: # for this user in user's homespace
1.553 albertel 3642: # - current conditional state info
1.325 www 3643: my $key=$uname.':'.$udom.':';
1.109 www 3644: my $status=
1.299 matthew 3645: &del('nohist_calculatedsheets',
1.391 matthew 3646: [$key.'studentcalc:'],
1.620 albertel 3647: $env{'course.'.$cid.'.domain'},
3648: $env{'course.'.$cid.'.num'})
1.133 albertel 3649: .' '.
3650: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3651: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3652: unless ($status eq 'ok ok') {
3653: &logthis('Could not devalidate spreadsheet '.
1.325 www 3654: $uname.' at '.$udom.' for '.
1.109 www 3655: $symb.': '.$status);
1.133 albertel 3656: }
1.553 albertel 3657: &delenv('user.state.'.$cid);
1.109 www 3658: }
3659: }
3660:
1.265 albertel 3661: sub get_scalar {
3662: my ($string,$end) = @_;
3663: my $value;
3664: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3665: $value = $1;
3666: } elsif ($$string =~ s/^([^&]*?)&//) {
3667: $value = $1;
3668: }
3669: return &unescape($value);
3670: }
3671:
3672: sub array2str {
3673: my (@array) = @_;
3674: my $result=&arrayref2str(\@array);
3675: $result=~s/^__ARRAY_REF__//;
3676: $result=~s/__END_ARRAY_REF__$//;
3677: return $result;
3678: }
3679:
1.204 albertel 3680: sub arrayref2str {
3681: my ($arrayref) = @_;
1.265 albertel 3682: my $result='__ARRAY_REF__';
1.204 albertel 3683: foreach my $elem (@$arrayref) {
1.265 albertel 3684: if(ref($elem) eq 'ARRAY') {
3685: $result.=&arrayref2str($elem).'&';
3686: } elsif(ref($elem) eq 'HASH') {
3687: $result.=&hashref2str($elem).'&';
3688: } elsif(ref($elem)) {
3689: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3690: } else {
3691: $result.=&escape($elem).'&';
3692: }
3693: }
3694: $result=~s/\&$//;
1.265 albertel 3695: $result .= '__END_ARRAY_REF__';
1.204 albertel 3696: return $result;
3697: }
3698:
1.168 albertel 3699: sub hash2str {
1.204 albertel 3700: my (%hash) = @_;
3701: my $result=&hashref2str(\%hash);
1.265 albertel 3702: $result=~s/^__HASH_REF__//;
3703: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3704: return $result;
3705: }
3706:
3707: sub hashref2str {
3708: my ($hashref)=@_;
1.265 albertel 3709: my $result='__HASH_REF__';
1.800 albertel 3710: foreach my $key (sort(keys(%$hashref))) {
3711: if (ref($key) eq 'ARRAY') {
3712: $result.=&arrayref2str($key).'=';
3713: } elsif (ref($key) eq 'HASH') {
3714: $result.=&hashref2str($key).'=';
3715: } elsif (ref($key)) {
1.265 albertel 3716: $result.='=';
1.800 albertel 3717: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3718: } else {
1.1056.4.32 raeburn 3719: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3720: }
3721:
1.800 albertel 3722: if(ref($hashref->{$key}) eq 'ARRAY') {
3723: $result.=&arrayref2str($hashref->{$key}).'&';
3724: } elsif(ref($hashref->{$key}) eq 'HASH') {
3725: $result.=&hashref2str($hashref->{$key}).'&';
3726: } elsif(ref($hashref->{$key})) {
1.265 albertel 3727: $result.='&';
1.800 albertel 3728: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3729: } else {
1.800 albertel 3730: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3731: }
3732: }
1.168 albertel 3733: $result=~s/\&$//;
1.265 albertel 3734: $result .= '__END_HASH_REF__';
1.168 albertel 3735: return $result;
3736: }
3737:
3738: sub str2hash {
1.265 albertel 3739: my ($string)=@_;
3740: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3741: return %$hash;
3742: }
3743:
3744: sub str2hashref {
1.168 albertel 3745: my ($string) = @_;
1.265 albertel 3746:
3747: my %hash;
3748:
3749: if($string !~ /^__HASH_REF__/) {
3750: if (! ($string eq '' || !defined($string))) {
3751: $hash{'error'}='Not hash reference';
3752: }
3753: return (\%hash, $string);
3754: }
3755:
3756: $string =~ s/^__HASH_REF__//;
3757:
3758: while($string !~ /^__END_HASH_REF__/) {
3759: #key
3760: my $key='';
3761: if($string =~ /^__HASH_REF__/) {
3762: ($key, $string)=&str2hashref($string);
3763: if(defined($key->{'error'})) {
3764: $hash{'error'}='Bad data';
3765: return (\%hash, $string);
3766: }
3767: } elsif($string =~ /^__ARRAY_REF__/) {
3768: ($key, $string)=&str2arrayref($string);
3769: if($key->[0] eq 'Array reference error') {
3770: $hash{'error'}='Bad data';
3771: return (\%hash, $string);
3772: }
3773: } else {
3774: $string =~ s/^(.*?)=//;
1.267 albertel 3775: $key=&unescape($1);
1.265 albertel 3776: }
3777: $string =~ s/^=//;
3778:
3779: #value
3780: my $value='';
3781: if($string =~ /^__HASH_REF__/) {
3782: ($value, $string)=&str2hashref($string);
3783: if(defined($value->{'error'})) {
3784: $hash{'error'}='Bad data';
3785: return (\%hash, $string);
3786: }
3787: } elsif($string =~ /^__ARRAY_REF__/) {
3788: ($value, $string)=&str2arrayref($string);
3789: if($value->[0] eq 'Array reference error') {
3790: $hash{'error'}='Bad data';
3791: return (\%hash, $string);
3792: }
3793: } else {
3794: $value=&get_scalar(\$string,'__END_HASH_REF__');
3795: }
3796: $string =~ s/^&//;
3797:
3798: $hash{$key}=$value;
1.204 albertel 3799: }
1.265 albertel 3800:
3801: $string =~ s/^__END_HASH_REF__//;
3802:
3803: return (\%hash, $string);
1.204 albertel 3804: }
3805:
3806: sub str2array {
1.265 albertel 3807: my ($string)=@_;
3808: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3809: return @$array;
3810: }
3811:
3812: sub str2arrayref {
1.204 albertel 3813: my ($string) = @_;
1.265 albertel 3814: my @array;
3815:
3816: if($string !~ /^__ARRAY_REF__/) {
3817: if (! ($string eq '' || !defined($string))) {
3818: $array[0]='Array reference error';
3819: }
3820: return (\@array, $string);
3821: }
3822:
3823: $string =~ s/^__ARRAY_REF__//;
3824:
3825: while($string !~ /^__END_ARRAY_REF__/) {
3826: my $value='';
3827: if($string =~ /^__HASH_REF__/) {
3828: ($value, $string)=&str2hashref($string);
3829: if(defined($value->{'error'})) {
3830: $array[0] ='Array reference error';
3831: return (\@array, $string);
3832: }
3833: } elsif($string =~ /^__ARRAY_REF__/) {
3834: ($value, $string)=&str2arrayref($string);
3835: if($value->[0] eq 'Array reference error') {
3836: $array[0] ='Array reference error';
3837: return (\@array, $string);
3838: }
3839: } else {
3840: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3841: }
3842: $string =~ s/^&//;
3843:
3844: push(@array, $value);
1.191 harris41 3845: }
1.265 albertel 3846:
3847: $string =~ s/^__END_ARRAY_REF__//;
3848:
3849: return (\@array, $string);
1.168 albertel 3850: }
3851:
1.167 albertel 3852: # -------------------------------------------------------------------Temp Store
3853:
1.168 albertel 3854: sub tmpreset {
3855: my ($symb,$namespace,$domain,$stuname) = @_;
3856: if (!$symb) {
3857: $symb=&symbread();
1.620 albertel 3858: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3859: }
3860: $symb=escape($symb);
3861:
1.620 albertel 3862: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3863: $namespace=~s/\//\_/g;
3864: $namespace=~s/\W//g;
3865:
1.620 albertel 3866: if (!$domain) { $domain=$env{'user.domain'}; }
3867: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3868: if ($domain eq 'public' && $stuname eq 'public') {
3869: $stuname=$ENV{'REMOTE_ADDR'};
3870: }
1.168 albertel 3871: my $path=$perlvar{'lonDaemons'}.'/tmp';
3872: my %hash;
3873: if (tie(%hash,'GDBM_File',
3874: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3875: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3876: foreach my $key (keys(%hash)) {
1.180 albertel 3877: if ($key=~ /:$symb/) {
1.168 albertel 3878: delete($hash{$key});
3879: }
3880: }
3881: }
3882: }
3883:
1.167 albertel 3884: sub tmpstore {
1.168 albertel 3885: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3886:
3887: if (!$symb) {
3888: $symb=&symbread();
1.620 albertel 3889: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3890: }
3891: $symb=escape($symb);
3892:
3893: if (!$namespace) {
3894: # I don't think we would ever want to store this for a course.
3895: # it seems this will only be used if we don't have a course.
1.620 albertel 3896: #$namespace=$env{'request.course.id'};
1.168 albertel 3897: #if (!$namespace) {
1.620 albertel 3898: $namespace=$env{'request.state'};
1.168 albertel 3899: #}
3900: }
3901: $namespace=~s/\//\_/g;
3902: $namespace=~s/\W//g;
1.620 albertel 3903: if (!$domain) { $domain=$env{'user.domain'}; }
3904: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3905: if ($domain eq 'public' && $stuname eq 'public') {
3906: $stuname=$ENV{'REMOTE_ADDR'};
3907: }
1.168 albertel 3908: my $now=time;
3909: my %hash;
3910: my $path=$perlvar{'lonDaemons'}.'/tmp';
3911: if (tie(%hash,'GDBM_File',
3912: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3913: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3914: $hash{"version:$symb"}++;
3915: my $version=$hash{"version:$symb"};
3916: my $allkeys='';
3917: foreach my $key (keys(%$storehash)) {
3918: $allkeys.=$key.':';
1.591 albertel 3919: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3920: }
3921: $hash{"$version:$symb:timestamp"}=$now;
3922: $allkeys.='timestamp';
3923: $hash{"$version:keys:$symb"}=$allkeys;
3924: if (untie(%hash)) {
3925: return 'ok';
3926: } else {
3927: return "error:$!";
3928: }
3929: } else {
3930: return "error:$!";
3931: }
3932: }
1.167 albertel 3933:
1.168 albertel 3934: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3935:
1.168 albertel 3936: sub tmprestore {
3937: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3938:
1.168 albertel 3939: if (!$symb) {
3940: $symb=&symbread();
1.620 albertel 3941: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3942: }
3943: $symb=escape($symb);
3944:
1.620 albertel 3945: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3946:
1.620 albertel 3947: if (!$domain) { $domain=$env{'user.domain'}; }
3948: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3949: if ($domain eq 'public' && $stuname eq 'public') {
3950: $stuname=$ENV{'REMOTE_ADDR'};
3951: }
1.168 albertel 3952: my %returnhash;
3953: $namespace=~s/\//\_/g;
3954: $namespace=~s/\W//g;
3955: my %hash;
3956: my $path=$perlvar{'lonDaemons'}.'/tmp';
3957: if (tie(%hash,'GDBM_File',
3958: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3959: &GDBM_READER(),0640)) {
1.168 albertel 3960: my $version=$hash{"version:$symb"};
3961: $returnhash{'version'}=$version;
3962: my $scope;
3963: for ($scope=1;$scope<=$version;$scope++) {
3964: my $vkeys=$hash{"$scope:keys:$symb"};
3965: my @keys=split(/:/,$vkeys);
3966: my $key;
3967: $returnhash{"$scope:keys"}=$vkeys;
3968: foreach $key (@keys) {
1.591 albertel 3969: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3970: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3971: }
3972: }
1.168 albertel 3973: if (!(untie(%hash))) {
3974: return "error:$!";
3975: }
3976: } else {
3977: return "error:$!";
3978: }
3979: return %returnhash;
1.167 albertel 3980: }
3981:
1.9 www 3982: # ----------------------------------------------------------------------- Store
3983:
3984: sub store {
1.124 www 3985: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3986: my $home='';
3987:
1.168 albertel 3988: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3989:
1.213 www 3990: $symb=&symbclean($symb);
1.122 albertel 3991: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3992:
1.620 albertel 3993: if (!$domain) { $domain=$env{'user.domain'}; }
3994: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3995:
3996: &devalidate($symb,$stuname,$domain);
1.109 www 3997:
3998: $symb=escape($symb);
1.187 www 3999: if (!$namespace) {
1.620 albertel 4000: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4001: return '';
4002: }
4003: }
1.620 albertel 4004: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4005:
4006: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4007: $$storehash{'host'}=$perlvar{'lonHostID'};
4008:
1.12 www 4009: my $namevalue='';
1.800 albertel 4010: foreach my $key (keys(%$storehash)) {
4011: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4012: }
1.12 www 4013: $namevalue=~s/\&$//;
1.187 www 4014: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4015: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4016: }
4017:
1.47 www 4018: # -------------------------------------------------------------- Critical Store
4019:
4020: sub cstore {
1.124 www 4021: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4022: my $home='';
4023:
1.168 albertel 4024: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4025:
1.213 www 4026: $symb=&symbclean($symb);
1.122 albertel 4027: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4028:
1.620 albertel 4029: if (!$domain) { $domain=$env{'user.domain'}; }
4030: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4031:
4032: &devalidate($symb,$stuname,$domain);
1.109 www 4033:
4034: $symb=escape($symb);
1.187 www 4035: if (!$namespace) {
1.620 albertel 4036: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4037: return '';
4038: }
4039: }
1.620 albertel 4040: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4041:
4042: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4043: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4044:
1.47 www 4045: my $namevalue='';
1.800 albertel 4046: foreach my $key (keys(%$storehash)) {
4047: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4048: }
1.47 www 4049: $namevalue=~s/\&$//;
1.187 www 4050: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4051: return critical
4052: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4053: }
4054:
1.9 www 4055: # --------------------------------------------------------------------- Restore
4056:
4057: sub restore {
1.124 www 4058: my ($symb,$namespace,$domain,$stuname) = @_;
4059: my $home='';
4060:
1.168 albertel 4061: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4062:
1.122 albertel 4063: if (!$symb) {
4064: unless ($symb=escape(&symbread())) { return ''; }
4065: } else {
1.213 www 4066: $symb=&escape(&symbclean($symb));
1.122 albertel 4067: }
1.188 www 4068: if (!$namespace) {
1.620 albertel 4069: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4070: return '';
4071: }
4072: }
1.620 albertel 4073: if (!$domain) { $domain=$env{'user.domain'}; }
4074: if (!$stuname) { $stuname=$env{'user.name'}; }
4075: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4076: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4077:
1.12 www 4078: my %returnhash=();
1.800 albertel 4079: foreach my $line (split(/\&/,$answer)) {
4080: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4081: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4082: }
1.75 www 4083: my $version;
4084: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4085: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4086: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4087: }
1.75 www 4088: }
1.13 www 4089: return %returnhash;
1.34 www 4090: }
4091:
4092: # ---------------------------------------------------------- Course Description
4093:
4094: sub coursedescription {
1.731 albertel 4095: my ($courseid,$args)=@_;
1.34 www 4096: $courseid=~s/^\///;
1.49 www 4097: $courseid=~s/\_/\//g;
1.34 www 4098: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4099: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4100: my $normalid=$cdomain.'_'.$cnum;
4101: # need to always cache even if we get errors otherwise we keep
4102: # trying and trying and trying to get the course description.
4103: my %envhash=();
4104: my %returnhash=();
1.731 albertel 4105:
4106: my $expiretime=600;
4107: if ($env{'request.course.id'} eq $normalid) {
4108: $expiretime=120;
4109: }
4110:
4111: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4112: if (!$args->{'freshen_cache'}
4113: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4114: foreach my $key (keys(%env)) {
4115: next if ($key !~ /^\Q$prefix\E(.*)/);
4116: my ($setting) = $1;
4117: $returnhash{$setting} = $env{$key};
4118: }
4119: return %returnhash;
4120: }
4121:
4122: # get the data agin
4123: if (!$args->{'one_time'}) {
4124: $envhash{'course.'.$normalid.'.last_cache'}=time;
4125: }
1.811 albertel 4126:
1.34 www 4127: if ($chome ne 'no_host') {
1.302 albertel 4128: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4129: if (!exists($returnhash{'con_lost'})) {
4130: $returnhash{'home'}= $chome;
4131: $returnhash{'domain'} = $cdomain;
4132: $returnhash{'num'} = $cnum;
1.741 raeburn 4133: if (!defined($returnhash{'type'})) {
4134: $returnhash{'type'} = 'Course';
4135: }
1.130 albertel 4136: while (my ($name,$value) = each %returnhash) {
1.53 www 4137: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4138: }
1.270 www 4139: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4140: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4141: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4142: $envhash{'course.'.$normalid.'.home'}=$chome;
4143: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4144: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4145: }
4146: }
1.731 albertel 4147: if (!$args->{'one_time'}) {
1.949 raeburn 4148: &appenv(\%envhash);
1.731 albertel 4149: }
1.302 albertel 4150: return %returnhash;
1.461 www 4151: }
4152:
1.1056.4.5 raeburn 4153: sub update_released_required {
4154: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4155: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4156: $cid = $env{'request.course.id'};
4157: $cdom = $env{'course.'.$cid.'.domain'};
4158: $cnum = $env{'course.'.$cid.'.num'};
4159: $chome = $env{'course.'.$cid.'.home'};
4160: }
4161: if ($needsrelease) {
4162: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4163: my $needsupdate;
4164: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4165: $needsupdate = 1;
4166: } else {
4167: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4168: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4169: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4170: $needsupdate = 1;
4171: }
4172: }
4173: if ($needsupdate) {
4174: my %needshash = (
4175: 'internal.releaserequired' => $needsrelease,
4176: );
4177: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4178: if ($putresult eq 'ok') {
4179: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4180: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4181: if (ref($crsinfo{$cid}) eq 'HASH') {
4182: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4183: &courseidput($cdom,\%crsinfo,$chome,'notime');
4184: }
4185: }
4186: }
4187: }
4188: return;
4189: }
4190:
1.461 www 4191: # -------------------------------------------------See if a user is privileged
4192:
4193: sub privileged {
4194: my ($username,$domain)=@_;
4195: my $rolesdump=&reply("dump:$domain:$username:roles",
4196: &homeserver($username,$domain));
1.1033 raeburn 4197: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4198: ($rolesdump =~ /^error:/)) {
4199: return 0;
4200: }
1.461 www 4201: my $now=time;
4202: if ($rolesdump ne '') {
1.800 albertel 4203: foreach my $entry (split(/&/,$rolesdump)) {
4204: if ($entry!~/^rolesdef_/) {
4205: my ($area,$role)=split(/=/,$entry);
1.461 www 4206: $area=~s/\_\w\w$//;
4207: my ($trole,$tend,$tstart)=split(/_/,$role);
4208: if (($trole eq 'dc') || ($trole eq 'su')) {
4209: my $active=1;
4210: if ($tend) {
4211: if ($tend<$now) { $active=0; }
4212: }
4213: if ($tstart) {
4214: if ($tstart>$now) { $active=0; }
4215: }
4216: if ($active) { return 1; }
4217: }
4218: }
4219: }
4220: }
4221: return 0;
1.9 www 4222: }
1.1 albertel 4223:
1.103 harris41 4224: # -------------------------------------------------------- Get user privileges
1.11 www 4225:
4226: sub rolesinit {
4227: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4228: my $now=time;
4229: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4230: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4231: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4232: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4233: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4234: return \%userroles;
4235: }
1.11 www 4236: my %allroles=();
1.678 raeburn 4237: my %allgroups=();
4238: my $group_privs;
1.11 www 4239:
4240: if ($rolesdump ne '') {
1.800 albertel 4241: foreach my $entry (split(/&/,$rolesdump)) {
4242: if ($entry!~/^rolesdef_/) {
4243: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4244: $area=~s/\_\w\w$//;
1.678 raeburn 4245: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4246: if ($role=~/^cr/) {
1.807 albertel 4247: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4248: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4249: ($tend,$tstart)=split('_',$trest);
4250: } else {
4251: $trole=$role;
4252: }
1.678 raeburn 4253: } elsif ($role =~ m|^gr/|) {
4254: ($trole,$tend,$tstart) = split(/_/,$role);
4255: ($trole,$group_privs) = split(/\//,$trole);
4256: $group_privs = &unescape($group_privs);
1.587 albertel 4257: } else {
4258: ($trole,$tend,$tstart)=split(/_/,$role);
4259: }
1.743 albertel 4260: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4261: $username);
4262: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4263: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4264: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4265: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4266: my $spec=$trole.'.'.$area;
4267: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4268: if ($trole =~ /^cr\//) {
1.567 raeburn 4269: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4270: } elsif ($trole eq 'gr') {
4271: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4272: } else {
1.567 raeburn 4273: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4274: }
1.12 www 4275: }
1.662 raeburn 4276: }
1.191 harris41 4277: }
1.743 albertel 4278: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4279: $userroles{'user.adv'} = $adv;
4280: $userroles{'user.author'} = $author;
1.620 albertel 4281: $env{'user.adv'}=$adv;
1.11 www 4282: }
1.743 albertel 4283: return \%userroles;
1.11 www 4284: }
4285:
1.567 raeburn 4286: sub set_arearole {
4287: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4288: # log the associated role with the area
4289: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4290: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4291: }
4292:
4293: sub custom_roleprivs {
4294: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4295: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4296: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4297: if (&hostname($homsvr) ne '') {
1.567 raeburn 4298: my ($rdummy,$roledef)=
4299: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4300: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4301: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4302: if (defined($syspriv)) {
1.1043 raeburn 4303: if ($trest =~ /^$match_community$/) {
4304: $syspriv =~ s/bre\&S//;
4305: }
1.567 raeburn 4306: $$allroles{'cm./'}.=':'.$syspriv;
4307: $$allroles{$spec.'./'}.=':'.$syspriv;
4308: }
4309: if ($tdomain ne '') {
4310: if (defined($dompriv)) {
4311: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4312: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4313: }
4314: if (($trest ne '') && (defined($coursepriv))) {
4315: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4316: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4317: }
4318: }
4319: }
4320: }
4321: }
4322:
1.678 raeburn 4323: sub group_roleprivs {
4324: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4325: my $access = 1;
4326: my $now = time;
4327: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4328: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4329: if ($access) {
1.811 albertel 4330: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4331: $$allgroups{$course}{$group} .=':'.$group_privs;
4332: }
4333: }
1.567 raeburn 4334:
4335: sub standard_roleprivs {
4336: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4337: if (defined($pr{$trole.':s'})) {
4338: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4339: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4340: }
4341: if ($tdomain ne '') {
4342: if (defined($pr{$trole.':d'})) {
4343: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4344: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4345: }
4346: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4347: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4348: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4349: }
4350: }
4351: }
4352:
4353: sub set_userprivs {
1.1056.4.2 raeburn 4354: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4355: my $author=0;
4356: my $adv=0;
1.678 raeburn 4357: my %grouproles = ();
4358: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4359: my @groupkeys;
1.1000 raeburn 4360: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4361: push(@groupkeys,$role);
4362: }
4363: if (ref($groups_roles) eq 'HASH') {
4364: foreach my $key (keys(%{$groups_roles})) {
4365: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4366: push(@groupkeys,$key);
4367: }
4368: }
4369: }
4370: if (@groupkeys > 0) {
4371: foreach my $role (@groupkeys) {
4372: my ($trole,$area,$sec,$extendedarea);
4373: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4374: $trole = $1;
4375: $area = $2;
4376: $sec = $3;
4377: $extendedarea = $area.$sec;
4378: if (exists($$allgroups{$area})) {
4379: foreach my $group (keys(%{$$allgroups{$area}})) {
4380: my $spec = $trole.'.'.$extendedarea;
4381: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4382: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4383: }
1.678 raeburn 4384: }
4385: }
4386: }
4387: }
4388: }
1.800 albertel 4389: foreach my $group (keys(%grouproles)) {
4390: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4391: }
1.800 albertel 4392: foreach my $role (keys(%{$allroles})) {
4393: my %thesepriv;
1.941 raeburn 4394: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4395: foreach my $item (split(/:/,$$allroles{$role})) {
4396: if ($item ne '') {
4397: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4398: if ($restrictions eq '') {
4399: $thesepriv{$privilege}='F';
4400: } elsif ($thesepriv{$privilege} ne 'F') {
4401: $thesepriv{$privilege}.=$restrictions;
4402: }
4403: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4404: }
4405: }
4406: my $thesestr='';
1.800 albertel 4407: foreach my $priv (keys(%thesepriv)) {
4408: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4409: }
4410: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4411: }
4412: return ($author,$adv);
4413: }
4414:
1.994 raeburn 4415: sub role_status {
1.1002 raeburn 4416: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4417: my @pwhere = ();
4418: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4419: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4420: unless (!defined($$role) || $$role eq '') {
4421: $$where=join('.',@pwhere);
4422: $$trolecode=$$role.'.'.$$where;
4423: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4424: $$tstatus='is';
4425: if ($$tstart && $$tstart>$then) {
4426: $$tstatus='future';
1.1034 raeburn 4427: if ($$tstart<$now) {
4428: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4429: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4430: my (%allroles,%allgroups,$group_privs,
4431: %groups_roles,@rolecodes);
1.1002 raeburn 4432: my %userroles = (
4433: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4434: );
1.1056.4.2 raeburn 4435: @rolecodes = ('cm');
1.1002 raeburn 4436: my $spec=$$role.'.'.$$where;
4437: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4438: if ($$role =~ /^cr\//) {
4439: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4440: push(@rolecodes,'cr');
1.1002 raeburn 4441: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4442: push(@rolecodes,$$role);
1.1002 raeburn 4443: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4444: $env{'user.name'});
1.1056.4.2 raeburn 4445: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4446: (undef,my $group_privs) = split(/\//,$trole);
4447: $group_privs = &unescape($group_privs);
4448: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4449: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4450: if (keys(%course_roles) > 0) {
4451: my ($tnum) = ($trest =~ /^($match_courseid)/);
4452: if ($tdomain ne '' && $tnum ne '') {
4453: foreach my $key (keys(%course_roles)) {
4454: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4455: my $crsrole = $1;
4456: my $crssec = $2;
4457: if ($crsrole =~ /^cr/) {
4458: unless (grep(/^cr$/,@rolecodes)) {
4459: push(@rolecodes,'cr');
4460: }
4461: } else {
4462: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4463: push(@rolecodes,$crsrole);
4464: }
4465: }
4466: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4467: if ($crssec ne '') {
4468: $rolekey .= '/'.$crssec;
4469: }
4470: $rolekey .= './';
4471: $groups_roles{$rolekey} = \@rolecodes;
4472: }
4473: }
4474: }
4475: }
1.1002 raeburn 4476: } else {
1.1056.4.2 raeburn 4477: push(@rolecodes,$$role);
1.1002 raeburn 4478: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4479: }
1.1056.4.2 raeburn 4480: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4481: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4482: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4483: }
4484: }
1.1034 raeburn 4485: $$tstatus = 'is';
1.1002 raeburn 4486: }
1.994 raeburn 4487: }
4488: if ($$tend) {
4489: if ($$tend<$then) {
4490: $$tstatus='expired';
4491: } elsif ($$tend<$now) {
4492: $$tstatus='will_not';
4493: }
4494: }
4495: }
4496: }
4497: }
4498:
4499: sub check_adhoc_privs {
1.1056.4.12 raeburn 4500: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4501: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4502: if ($env{$cckey}) {
4503: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4504: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4505: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12 raeburn 4506: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4507: }
4508: } else {
1.1056.4.12 raeburn 4509: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4510: }
4511: }
4512:
4513: sub set_adhoc_privileges {
4514: # role can be cc or ca
1.1056.4.12 raeburn 4515: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4516: my $area = '/'.$dcdom.'/'.$pickedcourse;
4517: my $spec = $role.'.'.$area;
4518: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4519: $env{'user.name'});
4520: my %ccrole = ();
4521: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4522: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4523: &appenv(\%userroles,[$role,'cm']);
4524: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12 raeburn 4525: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4526: &appenv( {'request.role' => $spec,
4527: 'request.role.domain' => $dcdom,
4528: 'request.course.sec' => ''
4529: }
4530: );
4531: my $tadv=0;
4532: if (&allowed('adv') eq 'F') { $tadv=1; }
4533: &appenv({'request.role.adv' => $tadv});
4534: }
1.994 raeburn 4535: }
4536:
1.12 www 4537: # --------------------------------------------------------------- get interface
4538:
4539: sub get {
1.131 albertel 4540: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4541: my $items='';
1.800 albertel 4542: foreach my $item (@$storearr) {
4543: $items.=&escape($item).'&';
1.191 harris41 4544: }
1.12 www 4545: $items=~s/\&$//;
1.620 albertel 4546: if (!$udomain) { $udomain=$env{'user.domain'}; }
4547: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4548: my $uhome=&homeserver($uname,$udomain);
4549:
1.133 albertel 4550: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4551: my @pairs=split(/\&/,$rep);
1.273 albertel 4552: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4553: return @pairs;
4554: }
1.15 www 4555: my %returnhash=();
1.42 www 4556: my $i=0;
1.800 albertel 4557: foreach my $item (@$storearr) {
4558: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4559: $i++;
1.191 harris41 4560: }
1.15 www 4561: return %returnhash;
1.27 www 4562: }
4563:
4564: # --------------------------------------------------------------- del interface
4565:
4566: sub del {
1.133 albertel 4567: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4568: my $items='';
1.800 albertel 4569: foreach my $item (@$storearr) {
4570: $items.=&escape($item).'&';
1.191 harris41 4571: }
1.984 neumanie 4572:
1.27 www 4573: $items=~s/\&$//;
1.620 albertel 4574: if (!$udomain) { $udomain=$env{'user.domain'}; }
4575: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4576: my $uhome=&homeserver($uname,$udomain);
4577: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4578: }
4579:
4580: # -------------------------------------------------------------- dump interface
4581:
4582: sub dump {
1.1056.4.10 raeburn 4583: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4584: if (!$udomain) { $udomain=$env{'user.domain'}; }
4585: if (!$uname) { $uname=$env{'user.name'}; }
4586: my $uhome=&homeserver($uname,$udomain);
4587: if ($regexp) {
4588: $regexp=&escape($regexp);
4589: } else {
4590: $regexp='.';
4591: }
1.1056.4.10 raeburn 4592: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4593: my @pairs=split(/\&/,$rep);
4594: my %returnhash=();
4595: foreach my $item (@pairs) {
4596: my ($key,$value)=split(/=/,$item,2);
4597: $key = &unescape($key);
4598: next if ($key =~ /^error: 2 /);
4599: $returnhash{$key}=&thaw_unescape($value);
4600: }
4601: return %returnhash;
1.407 www 4602: }
4603:
1.717 albertel 4604: # --------------------------------------------------------- dumpstore interface
4605:
4606: sub dumpstore {
4607: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4608: if (!$udomain) { $udomain=$env{'user.domain'}; }
4609: if (!$uname) { $uname=$env{'user.name'}; }
4610: my $uhome=&homeserver($uname,$udomain);
4611: if ($regexp) {
4612: $regexp=&escape($regexp);
4613: } else {
4614: $regexp='.';
4615: }
4616: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4617: my @pairs=split(/\&/,$rep);
4618: my %returnhash=();
4619: foreach my $item (@pairs) {
4620: my ($key,$value)=split(/=/,$item,2);
4621: next if ($key =~ /^error: 2 /);
4622: $returnhash{$key}=&thaw_unescape($value);
4623: }
4624: return %returnhash;
1.717 albertel 4625: }
4626:
1.407 www 4627: # -------------------------------------------------------------- keys interface
4628:
4629: sub getkeys {
4630: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4631: if (!$udomain) { $udomain=$env{'user.domain'}; }
4632: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4633: my $uhome=&homeserver($uname,$udomain);
4634: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4635: my @keyarray=();
1.800 albertel 4636: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4637: next if ($key =~ /^error: 2 /);
1.800 albertel 4638: push(@keyarray,&unescape($key));
1.407 www 4639: }
4640: return @keyarray;
1.318 matthew 4641: }
4642:
1.319 matthew 4643: # --------------------------------------------------------------- currentdump
4644: sub currentdump {
1.328 matthew 4645: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4646: $courseid = $env{'request.course.id'} if (! defined($courseid));
4647: $sdom = $env{'user.domain'} if (! defined($sdom));
4648: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4649: my $uhome = &homeserver($sname,$sdom);
4650: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4651: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4652: #
1.318 matthew 4653: my %returnhash=();
1.319 matthew 4654: #
4655: if ($rep eq "unknown_cmd") {
4656: # an old lond will not know currentdump
4657: # Do a dump and make it look like a currentdump
1.822 albertel 4658: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4659: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4660: my %hash = @tmp;
4661: @tmp=();
1.424 matthew 4662: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4663: } else {
4664: my @pairs=split(/\&/,$rep);
1.800 albertel 4665: foreach my $pair (@pairs) {
4666: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4667: my ($symb,$param) = split(/:/,$key);
4668: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4669: &thaw_unescape($value);
1.319 matthew 4670: }
1.191 harris41 4671: }
1.12 www 4672: return %returnhash;
1.424 matthew 4673: }
4674:
4675: sub convert_dump_to_currentdump{
4676: my %hash = %{shift()};
4677: my %returnhash;
4678: # Code ripped from lond, essentially. The only difference
4679: # here is the unescaping done by lonnet::dump(). Conceivably
4680: # we might run in to problems with parameter names =~ /^v\./
4681: while (my ($key,$value) = each(%hash)) {
4682: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4683: $symb = &unescape($symb);
4684: $param = &unescape($param);
1.424 matthew 4685: next if ($v eq 'version' || $symb eq 'keys');
4686: next if (exists($returnhash{$symb}) &&
4687: exists($returnhash{$symb}->{$param}) &&
4688: $returnhash{$symb}->{'v.'.$param} > $v);
4689: $returnhash{$symb}->{$param}=$value;
4690: $returnhash{$symb}->{'v.'.$param}=$v;
4691: }
4692: #
4693: # Remove all of the keys in the hashes which keep track of
4694: # the version of the parameter.
4695: while (my ($symb,$param_hash) = each(%returnhash)) {
4696: # use a foreach because we are going to delete from the hash.
4697: foreach my $key (keys(%$param_hash)) {
4698: delete($param_hash->{$key}) if ($key =~ /^v\./);
4699: }
4700: }
4701: return \%returnhash;
1.12 www 4702: }
4703:
1.627 albertel 4704: # ------------------------------------------------------ critical inc interface
4705:
4706: sub cinc {
4707: return &inc(@_,'critical');
4708: }
4709:
1.449 matthew 4710: # --------------------------------------------------------------- inc interface
4711:
4712: sub inc {
1.627 albertel 4713: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4714: if (!$udomain) { $udomain=$env{'user.domain'}; }
4715: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4716: my $uhome=&homeserver($uname,$udomain);
4717: my $items='';
4718: if (! ref($store)) {
4719: # got a single value, so use that instead
4720: $items = &escape($store).'=&';
4721: } elsif (ref($store) eq 'SCALAR') {
4722: $items = &escape($$store).'=&';
4723: } elsif (ref($store) eq 'ARRAY') {
4724: $items = join('=&',map {&escape($_);} @{$store});
4725: } elsif (ref($store) eq 'HASH') {
4726: while (my($key,$value) = each(%{$store})) {
4727: $items.= &escape($key).'='.&escape($value).'&';
4728: }
4729: }
4730: $items=~s/\&$//;
1.627 albertel 4731: if ($critical) {
4732: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4733: } else {
4734: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4735: }
1.449 matthew 4736: }
4737:
1.12 www 4738: # --------------------------------------------------------------- put interface
4739:
4740: sub put {
1.134 albertel 4741: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4742: if (!$udomain) { $udomain=$env{'user.domain'}; }
4743: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4744: my $uhome=&homeserver($uname,$udomain);
1.12 www 4745: my $items='';
1.800 albertel 4746: foreach my $item (keys(%$storehash)) {
4747: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4748: }
1.12 www 4749: $items=~s/\&$//;
1.134 albertel 4750: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4751: }
4752:
1.631 albertel 4753: # ------------------------------------------------------------ newput interface
4754:
4755: sub newput {
4756: my ($namespace,$storehash,$udomain,$uname)=@_;
4757: if (!$udomain) { $udomain=$env{'user.domain'}; }
4758: if (!$uname) { $uname=$env{'user.name'}; }
4759: my $uhome=&homeserver($uname,$udomain);
4760: my $items='';
4761: foreach my $key (keys(%$storehash)) {
4762: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4763: }
4764: $items=~s/\&$//;
4765: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4766: }
4767:
4768: # --------------------------------------------------------- putstore interface
4769:
1.524 raeburn 4770: sub putstore {
1.715 albertel 4771: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4772: if (!$udomain) { $udomain=$env{'user.domain'}; }
4773: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4774: my $uhome=&homeserver($uname,$udomain);
4775: my $items='';
1.715 albertel 4776: foreach my $key (keys(%$storehash)) {
4777: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4778: }
1.715 albertel 4779: $items=~s/\&$//;
1.716 albertel 4780: my $esc_symb=&escape($symb);
4781: my $esc_v=&escape($version);
1.715 albertel 4782: my $reply =
1.716 albertel 4783: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4784: $uhome);
4785: if ($reply eq 'unknown_cmd') {
1.716 albertel 4786: # gfall back to way things use to be done
1.715 albertel 4787: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4788: $uname);
1.524 raeburn 4789: }
1.715 albertel 4790: return $reply;
4791: }
4792:
4793: sub old_putstore {
1.716 albertel 4794: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4795: if (!$udomain) { $udomain=$env{'user.domain'}; }
4796: if (!$uname) { $uname=$env{'user.name'}; }
4797: my $uhome=&homeserver($uname,$udomain);
4798: my %newstorehash;
1.800 albertel 4799: foreach my $item (keys(%$storehash)) {
4800: my $key = $version.':'.&escape($symb).':'.$item;
4801: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4802: }
4803: my $items='';
4804: my %allitems = ();
1.800 albertel 4805: foreach my $item (keys(%newstorehash)) {
4806: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4807: my $key = $1.':keys:'.$2;
4808: $allitems{$key} .= $3.':';
4809: }
1.800 albertel 4810: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4811: }
1.800 albertel 4812: foreach my $item (keys(%allitems)) {
4813: $allitems{$item} =~ s/\:$//;
4814: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4815: }
4816: $items=~s/\&$//;
4817: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4818: }
4819:
1.47 www 4820: # ------------------------------------------------------ critical put interface
4821:
4822: sub cput {
1.134 albertel 4823: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4824: if (!$udomain) { $udomain=$env{'user.domain'}; }
4825: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4826: my $uhome=&homeserver($uname,$udomain);
1.47 www 4827: my $items='';
1.800 albertel 4828: foreach my $item (keys(%$storehash)) {
4829: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4830: }
1.47 www 4831: $items=~s/\&$//;
1.134 albertel 4832: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4833: }
4834:
4835: # -------------------------------------------------------------- eget interface
4836:
4837: sub eget {
1.133 albertel 4838: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4839: my $items='';
1.800 albertel 4840: foreach my $item (@$storearr) {
4841: $items.=&escape($item).'&';
1.191 harris41 4842: }
1.12 www 4843: $items=~s/\&$//;
1.620 albertel 4844: if (!$udomain) { $udomain=$env{'user.domain'}; }
4845: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4846: my $uhome=&homeserver($uname,$udomain);
4847: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4848: my @pairs=split(/\&/,$rep);
4849: my %returnhash=();
1.42 www 4850: my $i=0;
1.800 albertel 4851: foreach my $item (@$storearr) {
4852: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4853: $i++;
1.191 harris41 4854: }
1.12 www 4855: return %returnhash;
4856: }
4857:
1.667 albertel 4858: # ------------------------------------------------------------ tmpput interface
4859: sub tmpput {
1.802 raeburn 4860: my ($storehash,$server,$context)=@_;
1.667 albertel 4861: my $items='';
1.800 albertel 4862: foreach my $item (keys(%$storehash)) {
4863: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4864: }
4865: $items=~s/\&$//;
1.802 raeburn 4866: if (defined($context)) {
4867: $items .= ':'.&escape($context);
4868: }
1.667 albertel 4869: return &reply("tmpput:$items",$server);
4870: }
4871:
4872: # ------------------------------------------------------------ tmpget interface
4873: sub tmpget {
1.688 albertel 4874: my ($token,$server)=@_;
4875: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4876: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4877: my %returnhash;
4878: foreach my $item (split(/\&/,$rep)) {
4879: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4880: next if ($key =~ /^error: 2 /);
1.667 albertel 4881: $returnhash{&unescape($key)}=&thaw_unescape($value);
4882: }
4883: return %returnhash;
4884: }
4885:
1.688 albertel 4886: # ------------------------------------------------------------ tmpget interface
4887: sub tmpdel {
4888: my ($token,$server)=@_;
4889: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4890: return &reply("tmpdel:$token",$server);
4891: }
4892:
1.765 albertel 4893: # -------------------------------------------------- portfolio access checking
4894:
4895: sub portfolio_access {
1.766 albertel 4896: my ($requrl) = @_;
1.765 albertel 4897: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4898: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4899: if ($result) {
4900: my %setters;
4901: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4902: my ($startblock,$endblock) =
4903: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4904: if ($startblock && $endblock) {
4905: return 'B';
4906: }
4907: } else {
4908: my ($startblock,$endblock) =
4909: &Apache::loncommon::blockcheck(\%setters,'port');
4910: if ($startblock && $endblock) {
4911: return 'B';
4912: }
4913: }
4914: }
1.765 albertel 4915: if ($result eq 'ok') {
1.766 albertel 4916: return 'F';
1.765 albertel 4917: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4918: return 'A';
1.765 albertel 4919: }
1.766 albertel 4920: return '';
1.765 albertel 4921: }
4922:
4923: sub get_portfolio_access {
1.767 albertel 4924: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4925:
4926: if (!ref($access_hash)) {
4927: my $current_perms = &get_portfile_permissions($udom,$unum);
4928: my %access_controls = &get_access_controls($current_perms,$group,
4929: $file_name);
4930: $access_hash = $access_controls{$file_name};
4931: }
4932:
1.765 albertel 4933: my ($public,$guest,@domains,@users,@courses,@groups);
4934: my $now = time;
4935: if (ref($access_hash) eq 'HASH') {
4936: foreach my $key (keys(%{$access_hash})) {
4937: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4938: if ($start > $now) {
4939: next;
4940: }
4941: if ($end && $end<$now) {
4942: next;
4943: }
4944: if ($scope eq 'public') {
4945: $public = $key;
4946: last;
4947: } elsif ($scope eq 'guest') {
4948: $guest = $key;
4949: } elsif ($scope eq 'domains') {
4950: push(@domains,$key);
4951: } elsif ($scope eq 'users') {
4952: push(@users,$key);
4953: } elsif ($scope eq 'course') {
4954: push(@courses,$key);
4955: } elsif ($scope eq 'group') {
4956: push(@groups,$key);
4957: }
4958: }
4959: if ($public) {
4960: return 'ok';
4961: }
4962: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4963: if ($guest) {
4964: return $guest;
4965: }
4966: } else {
4967: if (@domains > 0) {
4968: foreach my $domkey (@domains) {
4969: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4970: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4971: return 'ok';
4972: }
4973: }
4974: }
4975: }
4976: if (@users > 0) {
4977: foreach my $userkey (@users) {
1.865 raeburn 4978: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4979: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4980: if (ref($item) eq 'HASH') {
4981: if (($item->{'uname'} eq $env{'user.name'}) &&
4982: ($item->{'udom'} eq $env{'user.domain'})) {
4983: return 'ok';
4984: }
4985: }
4986: }
4987: }
1.765 albertel 4988: }
4989: }
4990: my %roleshash;
4991: my @courses_and_groups = @courses;
4992: push(@courses_and_groups,@groups);
4993: if (@courses_and_groups > 0) {
4994: my (%allgroups,%allroles);
4995: my ($start,$end,$role,$sec,$group);
4996: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4997: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4998: my $cid = $2.'_'.$3;
4999: if ($1 eq 'gr') {
5000: $group = $4;
5001: $allgroups{$cid}{$group} = $env{$envkey};
5002: } else {
5003: if ($4 eq '') {
5004: $sec = 'none';
5005: } else {
5006: $sec = $4;
5007: }
5008: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5009: }
1.811 albertel 5010: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5011: my $cid = $2.'_'.$3;
5012: if ($4 eq '') {
5013: $sec = 'none';
5014: } else {
5015: $sec = $4;
5016: }
5017: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5018: }
5019: }
5020: if (keys(%allroles) == 0) {
5021: return;
5022: }
5023: foreach my $key (@courses_and_groups) {
5024: my %content = %{$$access_hash{$key}};
5025: my $cnum = $content{'number'};
5026: my $cdom = $content{'domain'};
5027: my $cid = $cdom.'_'.$cnum;
5028: if (!exists($allroles{$cid})) {
5029: next;
5030: }
5031: foreach my $role_id (keys(%{$content{'roles'}})) {
5032: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5033: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5034: my @status = @{$content{'roles'}{$role_id}{'access'}};
5035: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5036: foreach my $role (keys(%{$allroles{$cid}})) {
5037: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5038: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5039: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5040: if (grep/^all$/,@sections) {
5041: return 'ok';
5042: } else {
5043: if (grep/^$sec$/,@sections) {
5044: return 'ok';
5045: }
5046: }
5047: }
5048: }
5049: if (keys(%{$allgroups{$cid}}) == 0) {
5050: if (grep/^none$/,@groups) {
5051: return 'ok';
5052: }
5053: } else {
5054: if (grep/^all$/,@groups) {
5055: return 'ok';
5056: }
5057: foreach my $group (keys(%{$allgroups{$cid}})) {
5058: if (grep/^$group$/,@groups) {
5059: return 'ok';
5060: }
5061: }
5062: }
5063: }
5064: }
5065: }
5066: }
5067: }
5068: if ($guest) {
5069: return $guest;
5070: }
5071: }
5072: }
5073: return;
5074: }
5075:
5076: sub course_group_datechecker {
5077: my ($dates,$now,$status) = @_;
5078: my ($start,$end) = split(/\./,$dates);
5079: if (!$start && !$end) {
5080: return 'ok';
5081: }
5082: if (grep/^active$/,@{$status}) {
5083: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5084: return 'ok';
5085: }
5086: }
5087: if (grep/^previous$/,@{$status}) {
5088: if ($end > $now ) {
5089: return 'ok';
5090: }
5091: }
5092: if (grep/^future$/,@{$status}) {
5093: if ($start > $now) {
5094: return 'ok';
5095: }
5096: }
5097: return;
5098: }
5099:
5100: sub parse_portfolio_url {
5101: my ($url) = @_;
5102:
5103: my ($type,$udom,$unum,$group,$file_name);
5104:
1.823 albertel 5105: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5106: $type = 1;
5107: $udom = $1;
5108: $unum = $2;
5109: $file_name = $3;
1.823 albertel 5110: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5111: $type = 2;
5112: $udom = $1;
5113: $unum = $2;
5114: $group = $3;
5115: $file_name = $3.'/'.$4;
5116: }
5117: if (wantarray) {
5118: return ($type,$udom,$unum,$file_name,$group);
5119: }
5120: return $type;
5121: }
5122:
5123: sub is_portfolio_url {
5124: my ($url) = @_;
5125: return scalar(&parse_portfolio_url($url));
5126: }
5127:
1.798 raeburn 5128: sub is_portfolio_file {
5129: my ($file) = @_;
1.820 raeburn 5130: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5131: return 1;
5132: }
5133: return;
5134: }
5135:
1.976 raeburn 5136: sub usertools_access {
1.1056.4.9 raeburn 5137: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5138: my ($access,%tools);
5139: if ($context eq '') {
5140: $context = 'tools';
5141: }
5142: if ($context eq 'requestcourses') {
5143: %tools = (
5144: official => 1,
5145: unofficial => 1,
1.1006 raeburn 5146: community => 1,
1.985 raeburn 5147: );
5148: } else {
5149: %tools = (
5150: aboutme => 1,
5151: blog => 1,
5152: portfolio => 1,
5153: );
5154: }
1.976 raeburn 5155: return if (!defined($tools{$tool}));
5156:
5157: if ((!defined($udom)) || (!defined($uname))) {
5158: $udom = $env{'user.domain'};
5159: $uname = $env{'user.name'};
5160: }
5161:
1.978 raeburn 5162: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5163: if ($action ne 'reload') {
1.985 raeburn 5164: if ($context eq 'requestcourses') {
5165: return $env{'environment.canrequest.'.$tool};
5166: } else {
5167: return $env{'environment.availabletools.'.$tool};
5168: }
5169: }
1.976 raeburn 5170: }
5171:
5172: my ($toolstatus,$inststatus);
5173:
1.985 raeburn 5174: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5175: ($action ne 'reload')) {
5176: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5177: $inststatus = $env{'environment.inststatus'};
5178: } else {
1.1056.4.9 raeburn 5179: if (ref($userenvref) eq 'HASH') {
5180: $toolstatus = $userenvref->{$context.'.'.$tool};
5181: $inststatus = $userenvref->{'inststatus'};
5182: } else {
5183: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5184: $toolstatus = $userenv{$context.'.'.$tool};
5185: $inststatus = $userenv{'inststatus'};
5186: }
1.976 raeburn 5187: }
5188:
5189: if ($toolstatus ne '') {
5190: if ($toolstatus) {
5191: $access = 1;
5192: } else {
5193: $access = 0;
5194: }
5195: return $access;
5196: }
5197:
1.1056.4.9 raeburn 5198: my ($is_adv,%domdef);
5199: if (ref($is_advref) eq 'HASH') {
5200: $is_adv = $is_advref->{'is_adv'};
5201: } else {
5202: $is_adv = &is_advanced_user($udom,$uname);
5203: }
5204: if (ref($domdefref) eq 'HASH') {
5205: %domdef = %{$domdefref};
5206: } else {
5207: %domdef = &get_domain_defaults($udom);
5208: }
1.976 raeburn 5209: if (ref($domdef{$tool}) eq 'HASH') {
5210: if ($is_adv) {
5211: if ($domdef{$tool}{'_LC_adv'} ne '') {
5212: if ($domdef{$tool}{'_LC_adv'}) {
5213: $access = 1;
5214: } else {
5215: $access = 0;
5216: }
5217: return $access;
5218: }
5219: }
5220: if ($inststatus ne '') {
5221: my ($hasaccess,$hasnoaccess);
5222: foreach my $affiliation (split(/:/,$inststatus)) {
5223: if ($domdef{$tool}{$affiliation} ne '') {
5224: if ($domdef{$tool}{$affiliation}) {
5225: $hasaccess = 1;
5226: } else {
5227: $hasnoaccess = 1;
5228: }
5229: }
5230: }
5231: if ($hasaccess || $hasnoaccess) {
5232: if ($hasaccess) {
5233: $access = 1;
5234: } elsif ($hasnoaccess) {
5235: $access = 0;
5236: }
5237: return $access;
5238: }
5239: } else {
5240: if ($domdef{$tool}{'default'} ne '') {
5241: if ($domdef{$tool}{'default'}) {
5242: $access = 1;
5243: } elsif ($domdef{$tool}{'default'} == 0) {
5244: $access = 0;
5245: }
5246: return $access;
5247: }
5248: }
5249: } else {
1.985 raeburn 5250: if ($context eq 'tools') {
5251: $access = 1;
5252: } else {
5253: $access = 0;
5254: }
1.976 raeburn 5255: return $access;
5256: }
5257: }
5258:
1.1050 raeburn 5259: sub is_course_owner {
5260: my ($cdom,$cnum,$udom,$uname) = @_;
5261: if (($udom eq '') || ($uname eq '')) {
5262: $udom = $env{'user.domain'};
5263: $uname = $env{'user.name'};
5264: }
5265: unless (($udom eq '') || ($uname eq '')) {
5266: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5267: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5268: return 1;
5269: } else {
5270: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5271: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5272: return 1;
5273: }
5274: }
5275: }
5276: }
5277: return;
5278: }
5279:
1.976 raeburn 5280: sub is_advanced_user {
5281: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5282: if ($udom ne '' && $uname ne '') {
5283: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5284: return $env{'user.adv'};
5285: }
5286: }
1.976 raeburn 5287: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5288: my %allroles;
5289: my $is_adv;
5290: foreach my $role (keys(%roleshash)) {
5291: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5292: my $area = '/'.$tdomain.'/'.$trest;
5293: if ($sec ne '') {
5294: $area .= '/'.$sec;
5295: }
5296: if (($area ne '') && ($trole ne '')) {
5297: my $spec=$trole.'.'.$area;
5298: if ($trole =~ /^cr\//) {
5299: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5300: } elsif ($trole ne 'gr') {
5301: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5302: }
5303: }
5304: }
5305: foreach my $role (keys(%allroles)) {
5306: last if ($is_adv);
5307: foreach my $item (split(/:/,$allroles{$role})) {
5308: if ($item ne '') {
5309: my ($privilege,$restrictions)=split(/&/,$item);
5310: if ($privilege eq 'adv') {
5311: $is_adv = 1;
5312: last;
5313: }
5314: }
5315: }
5316: }
5317: return $is_adv;
5318: }
1.798 raeburn 5319:
1.1035 raeburn 5320: sub check_can_request {
1.1036 raeburn 5321: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5322: my $canreq = 0;
5323: my ($types,$typename) = &Apache::loncommon::course_types();
5324: my @options = ('approval','validate','autolimit');
5325: my $optregex = join('|',@options);
5326: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5327: foreach my $type (@{$types}) {
5328: if (&usertools_access($env{'user.name'},
5329: $env{'user.domain'},
5330: $type,undef,'requestcourses')) {
5331: $canreq ++;
1.1036 raeburn 5332: if (ref($request_domains) eq 'HASH') {
5333: push(@{$request_domains->{$type}},$env{'user.domain'});
5334: }
1.1035 raeburn 5335: if ($dom eq $env{'user.domain'}) {
5336: $can_request->{$type} = 1;
5337: }
5338: }
5339: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5340: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5341: if (@curr > 0) {
1.1036 raeburn 5342: foreach my $item (@curr) {
5343: if (ref($request_domains) eq 'HASH') {
5344: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5345: if ($otherdom ne '') {
5346: if (ref($request_domains->{$type}) eq 'ARRAY') {
5347: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5348: push(@{$request_domains->{$type}},$otherdom);
5349: }
5350: } else {
5351: push(@{$request_domains->{$type}},$otherdom);
5352: }
5353: }
5354: }
5355: }
5356: unless($dom eq $env{'user.domain'}) {
5357: $canreq ++;
1.1035 raeburn 5358: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5359: $can_request->{$type} = 1;
5360: }
5361: }
5362: }
5363: }
5364: }
5365: }
5366: return $canreq;
5367: }
5368:
1.341 www 5369: # ---------------------------------------------- Custom access rule evaluation
5370:
5371: sub customaccess {
5372: my ($priv,$uri)=@_;
1.807 albertel 5373: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5374: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5375: $udom = &LONCAPA::clean_domain($udom);
5376: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5377: my $access=0;
1.800 albertel 5378: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5379: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5380: if ($type eq 'user') {
5381: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5382: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5383: if ($tdom) {
5384: if ($tdom ne $env{'user.domain'}) { next; }
5385: }
1.896 albertel 5386: if ($tuname) {
5387: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5388: }
5389: $access=($effect eq 'allow');
5390: last;
5391: }
5392: } else {
5393: if ($role) {
5394: if ($role ne $urole) { next; }
5395: }
5396: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5397: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5398: if ($tdom) {
5399: if ($tdom ne $udom) { next; }
5400: }
5401: if ($tcrs) {
5402: if ($tcrs ne $ucrs) { next; }
5403: }
5404: if ($tsec) {
5405: if ($tsec ne $usec) { next; }
5406: }
5407: $access=($effect eq 'allow');
5408: last;
5409: }
5410: if ($realm eq '' && $role eq '') {
5411: $access=($effect eq 'allow');
5412: }
1.402 bowersj2 5413: }
1.341 www 5414: }
5415: return $access;
5416: }
5417:
1.103 harris41 5418: # ------------------------------------------------- Check for a user privilege
1.12 www 5419:
5420: sub allowed {
1.810 raeburn 5421: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5422: my $ver_orguri=$uri;
1.439 www 5423: $uri=&deversion($uri);
1.152 www 5424: my $orguri=$uri;
1.52 www 5425: $uri=&declutter($uri);
1.809 raeburn 5426:
1.810 raeburn 5427: if ($priv eq 'evb') {
5428: # Evade communication block restrictions for specified role in a course
5429: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5430: return $1;
5431: } else {
5432: return;
5433: }
5434: }
5435:
1.620 albertel 5436: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5437: # Free bre access to adm and meta resources
1.775 albertel 5438: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5439: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5440: && ($priv eq 'bre')) {
1.14 www 5441: return 'F';
1.159 www 5442: }
5443:
1.545 banghart 5444: # Free bre access to user's own portfolio contents
1.714 raeburn 5445: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5446: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5447: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5448: my %setters;
5449: my ($startblock,$endblock) =
5450: &Apache::loncommon::blockcheck(\%setters,'port');
5451: if ($startblock && $endblock) {
5452: return 'B';
5453: } else {
5454: return 'F';
5455: }
1.545 banghart 5456: }
5457:
1.762 raeburn 5458: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5459: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5460: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5461: if (exists($env{'request.course.id'})) {
5462: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5463: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5464: if (($domain eq $cdom) && ($name eq $cnum)) {
5465: my $courseprivid=$env{'request.course.id'};
5466: $courseprivid=~s/\_/\//;
5467: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5468: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5469: return $1;
1.762 raeburn 5470: } else {
5471: if ($env{'request.course.sec'}) {
5472: $courseprivid.='/'.$env{'request.course.sec'};
5473: }
5474: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5475: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5476: return $2;
5477: }
1.714 raeburn 5478: }
5479: }
5480: }
5481: }
5482:
1.159 www 5483: # Free bre to public access
5484:
5485: if ($priv eq 'bre') {
1.238 www 5486: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5487: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5488: return 'F';
5489: }
1.238 www 5490: if ($copyright eq 'priv') {
5491: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5492: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5493: return '';
5494: }
5495: }
5496: if ($copyright eq 'domain') {
5497: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5498: unless (($env{'user.domain'} eq $1) ||
5499: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5500: return '';
5501: }
1.262 matthew 5502: }
1.620 albertel 5503: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5504: # Library role, so allow browsing of resources in this domain.
5505: return 'F';
1.238 www 5506: }
1.341 www 5507: if ($copyright eq 'custom') {
5508: unless (&customaccess($priv,$uri)) { return ''; }
5509: }
1.14 www 5510: }
1.264 matthew 5511: # Domain coordinator is trying to create a course
1.620 albertel 5512: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5513: # uri is the requested domain in this case.
5514: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5515: # a role of dc for the domain in question.
1.620 albertel 5516: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5517: }
1.29 www 5518:
1.52 www 5519: my $thisallowed='';
5520: my $statecond=0;
5521: my $courseprivid='';
5522:
1.1039 raeburn 5523: my $ownaccess;
1.1043 raeburn 5524: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5525: if (($priv eq 'bro') && ($env{'user.author'})) {
5526: if ($uri eq '') {
5527: $ownaccess = 1;
5528: } else {
5529: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5530: my $udom = $env{'user.domain'};
5531: my $uname = $env{'user.name'};
5532: if ($uri =~ m{^\Q$udom\E/?$}) {
5533: $ownaccess = 1;
1.1040 raeburn 5534: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5535: unless ($uri =~ m{\.\./}) {
5536: $ownaccess = 1;
5537: }
5538: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5539: my $now = time;
5540: if ($uri =~ m{^([^/]+)/?$}) {
5541: my $adom = $1;
5542: foreach my $key (keys(%env)) {
1.1042 raeburn 5543: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5544: my ($start,$end) = split('.',$env{$key});
5545: if (($now >= $start) && (!$end || $end < $now)) {
5546: $ownaccess = 1;
5547: last;
5548: }
5549: }
5550: }
5551: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5552: my $adom = $1;
5553: my $aname = $2;
1.1042 raeburn 5554: foreach my $role ('ca','aa') {
5555: if ($env{"user.role.$role./$adom/$aname"}) {
5556: my ($start,$end) =
5557: split('.',$env{"user.role.$role./$adom/$aname"});
5558: if (($now >= $start) && (!$end || $end < $now)) {
5559: $ownaccess = 1;
5560: last;
5561: }
1.1039 raeburn 5562: }
5563: }
5564: }
5565: }
5566: }
5567: }
5568: }
5569:
1.52 www 5570: # Course
5571:
1.620 albertel 5572: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5573: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5574: $thisallowed.=$1;
5575: }
1.52 www 5576: }
1.29 www 5577:
1.52 www 5578: # Domain
5579:
1.620 albertel 5580: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5581: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5582: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5583: $thisallowed.=$1;
5584: }
1.12 www 5585: }
1.52 www 5586:
5587: # Course: uri itself is a course
1.66 www 5588: my $courseuri=$uri;
5589: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5590: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5591:
1.620 albertel 5592: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5593: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5594: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5595: $thisallowed.=$1;
5596: }
1.12 www 5597: }
1.29 www 5598:
1.665 albertel 5599: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5600: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5601: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5602: $thisallowed='';
1.671 raeburn 5603: my ($match)=&is_on_map($uri);
5604: if ($match) {
5605: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5606: =~/\Q$priv\E\&([^\:]*)/) {
5607: $thisallowed.=$1;
5608: }
5609: } else {
1.705 albertel 5610: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5611: if ($refuri) {
5612: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5613: $thisallowed='F';
1.671 raeburn 5614: } else {
5615: $refuri=&declutter($refuri);
5616: my ($match) = &is_on_map($refuri);
5617: if ($match) {
5618: $thisallowed='F';
5619: }
1.669 raeburn 5620: }
1.671 raeburn 5621: }
5622: }
1.314 www 5623: }
1.492 albertel 5624:
1.766 albertel 5625: if ($priv eq 'bre'
5626: && $thisallowed ne 'F'
5627: && $thisallowed ne '2'
5628: && &is_portfolio_url($uri)) {
5629: $thisallowed = &portfolio_access($uri);
5630: }
5631:
1.52 www 5632: # Full access at system, domain or course-wide level? Exit.
1.29 www 5633: if ($thisallowed=~/F/) {
5634: return 'F';
5635: }
5636:
1.52 www 5637: # If this is generating or modifying users, exit with special codes
1.29 www 5638:
1.643 www 5639: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5640: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5641: my ($audom,$auname)=split('/',$uri);
1.643 www 5642: # no author name given, so this just checks on the general right to make a co-author in this domain
5643: unless ($auname) { return $thisallowed; }
5644: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5645: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5646: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5647: ($audom ne $env{'request.role.domain'}))) { return ''; }
5648: }
1.52 www 5649: return $thisallowed;
5650: }
5651: #
1.103 harris41 5652: # Gathered so far: system, domain and course wide privileges
1.52 www 5653: #
5654: # Course: See if uri or referer is an individual resource that is part of
5655: # the course
5656:
1.620 albertel 5657: if ($env{'request.course.id'}) {
1.232 www 5658:
1.620 albertel 5659: $courseprivid=$env{'request.course.id'};
5660: if ($env{'request.course.sec'}) {
5661: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5662: }
5663: $courseprivid=~s/\_/\//;
5664: my $checkreferer=1;
1.232 www 5665: my ($match,$cond)=&is_on_map($uri);
5666: if ($match) {
5667: $statecond=$cond;
1.620 albertel 5668: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5669: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5670: $thisallowed.=$1;
5671: $checkreferer=0;
5672: }
1.29 www 5673: }
1.83 www 5674:
1.148 www 5675: if ($checkreferer) {
1.620 albertel 5676: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5677: unless ($refuri) {
1.800 albertel 5678: foreach my $key (keys(%env)) {
5679: if ($key=~/^httpref\..*\*/) {
5680: my $pattern=$key;
1.156 www 5681: $pattern=~s/^httpref\.\/res\///;
1.148 www 5682: $pattern=~s/\*/\[\^\/\]\+/g;
5683: $pattern=~s/\//\\\//g;
1.152 www 5684: if ($orguri=~/$pattern/) {
1.800 albertel 5685: $refuri=$env{$key};
1.148 www 5686: }
5687: }
1.191 harris41 5688: }
1.148 www 5689: }
1.232 www 5690:
1.148 www 5691: if ($refuri) {
1.152 www 5692: $refuri=&declutter($refuri);
1.232 www 5693: my ($match,$cond)=&is_on_map($refuri);
5694: if ($match) {
5695: my $refstatecond=$cond;
1.620 albertel 5696: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5697: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5698: $thisallowed.=$1;
1.53 www 5699: $uri=$refuri;
5700: $statecond=$refstatecond;
1.52 www 5701: }
5702: }
1.148 www 5703: }
1.29 www 5704: }
1.52 www 5705: }
1.29 www 5706:
1.52 www 5707: #
1.103 harris41 5708: # Gathered now: all privileges that could apply, and condition number
1.52 www 5709: #
5710: #
5711: # Full or no access?
5712: #
1.29 www 5713:
1.52 www 5714: if ($thisallowed=~/F/) {
5715: return 'F';
5716: }
1.29 www 5717:
1.52 www 5718: unless ($thisallowed) {
5719: return '';
5720: }
1.29 www 5721:
1.52 www 5722: # Restrictions exist, deal with them
5723: #
5724: # C:according to course preferences
5725: # R:according to resource settings
5726: # L:unless locked
5727: # X:according to user session state
5728: #
5729:
5730: # Possibly locked functionality, check all courses
1.54 www 5731: # Locks might take effect only after 10 minutes cache expiration for other
5732: # courses, and 2 minutes for current course
1.52 www 5733:
5734: my $envkey;
5735: if ($thisallowed=~/L/) {
1.1000 raeburn 5736: foreach $envkey (keys(%env)) {
1.54 www 5737: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5738: my $courseid=$2;
5739: my $roleid=$1.'.'.$2;
1.92 www 5740: $courseid=~s/^\///;
1.54 www 5741: my $expiretime=600;
1.620 albertel 5742: if ($env{'request.role'} eq $roleid) {
1.54 www 5743: $expiretime=120;
5744: }
5745: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5746: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5747: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5748: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5749: }
1.620 albertel 5750: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5751: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5752: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5753: &log($env{'user.domain'},$env{'user.name'},
5754: $env{'user.home'},
1.57 www 5755: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5756: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5757: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5758: return '';
5759: }
5760: }
1.620 albertel 5761: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5762: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5763: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5764: &log($env{'user.domain'},$env{'user.name'},
5765: $env{'user.home'},
1.57 www 5766: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5767: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5768: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5769: return '';
5770: }
5771: }
5772: }
1.29 www 5773: }
1.52 www 5774: }
5775:
5776: #
5777: # Rest of the restrictions depend on selected course
5778: #
5779:
1.620 albertel 5780: unless ($env{'request.course.id'}) {
1.766 albertel 5781: if ($thisallowed eq 'A') {
5782: return 'A';
1.814 raeburn 5783: } elsif ($thisallowed eq 'B') {
5784: return 'B';
1.766 albertel 5785: } else {
5786: return '1';
5787: }
1.52 www 5788: }
1.29 www 5789:
1.52 www 5790: #
5791: # Now user is definitely in a course
5792: #
1.53 www 5793:
5794:
5795: # Course preferences
5796:
5797: if ($thisallowed=~/C/) {
1.620 albertel 5798: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5799: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5800: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5801: =~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5802: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5803: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5804: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5805: $env{'request.course.id'});
5806: }
1.237 www 5807: return '';
5808: }
5809:
1.620 albertel 5810: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5811: =~/\Q$unamedom\E/) {
1.1056.4.22 raeburn 5812: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5813: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5814: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5815: $env{'request.course.id'});
5816: }
1.54 www 5817: return '';
5818: }
1.53 www 5819: }
5820:
5821: # Resource preferences
5822:
5823: if ($thisallowed=~/R/) {
1.620 albertel 5824: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5825: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22 raeburn 5826: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 5827: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5828: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5829: }
5830: return '';
1.54 www 5831: }
1.53 www 5832: }
1.30 www 5833:
1.246 www 5834: # Restricted by state or randomout?
1.30 www 5835:
1.52 www 5836: if ($thisallowed=~/X/) {
1.620 albertel 5837: if ($env{'acc.randomout'}) {
1.579 albertel 5838: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5839: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5840: return '';
5841: }
1.247 www 5842: }
5843: if (&condval($statecond)) {
1.52 www 5844: return '2';
5845: } else {
5846: return '';
5847: }
5848: }
1.30 www 5849:
1.766 albertel 5850: if ($thisallowed eq 'A') {
5851: return 'A';
1.814 raeburn 5852: } elsif ($thisallowed eq 'B') {
5853: return 'B';
1.766 albertel 5854: }
1.52 www 5855: return 'F';
1.232 www 5856: }
5857:
1.710 albertel 5858: sub split_uri_for_cond {
5859: my $uri=&deversion(&declutter(shift));
5860: my @uriparts=split(/\//,$uri);
5861: my $filename=pop(@uriparts);
5862: my $pathname=join('/',@uriparts);
5863: return ($pathname,$filename);
5864: }
1.232 www 5865: # --------------------------------------------------- Is a resource on the map?
5866:
5867: sub is_on_map {
1.710 albertel 5868: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5869: #Trying to find the conditional for the file
1.620 albertel 5870: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5871: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5872: if ($match) {
1.289 bowersj2 5873: return (1,$1);
5874: } else {
1.434 www 5875: return (0,0);
1.289 bowersj2 5876: }
1.12 www 5877: }
5878:
1.427 www 5879: # --------------------------------------------------------- Get symb from alias
5880:
5881: sub get_symb_from_alias {
5882: my $symb=shift;
5883: my ($map,$resid,$url)=&decode_symb($symb);
5884: # Already is a symb
5885: if ($url) { return $symb; }
5886: # Must be an alias
5887: my $aliassymb='';
5888: my %bighash;
1.620 albertel 5889: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5890: &GDBM_READER(),0640)) {
5891: my $rid=$bighash{'mapalias_'.$symb};
5892: if ($rid) {
5893: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5894: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5895: $resid,$bighash{'src_'.$rid});
1.427 www 5896: }
5897: untie %bighash;
5898: }
5899: return $aliassymb;
5900: }
5901:
1.12 www 5902: # ----------------------------------------------------------------- Define Role
5903:
5904: sub definerole {
5905: if (allowed('mcr','/')) {
5906: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5907: foreach my $role (split(':',$sysrole)) {
5908: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5909: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5910: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5911: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5912: return "refused:s:$crole&$cqual";
5913: }
5914: }
1.191 harris41 5915: }
1.800 albertel 5916: foreach my $role (split(':',$domrole)) {
5917: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5918: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5919: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5920: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5921: return "refused:d:$crole&$cqual";
5922: }
5923: }
1.191 harris41 5924: }
1.800 albertel 5925: foreach my $role (split(':',$courole)) {
5926: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5927: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5928: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5929: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5930: return "refused:c:$crole&$cqual";
5931: }
5932: }
1.191 harris41 5933: }
1.620 albertel 5934: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5935: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5936: "rolesdef_$rolename=".
5937: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5938: return reply($command,$env{'user.home'});
1.12 www 5939: } else {
5940: return 'refused';
5941: }
1.105 harris41 5942: }
5943:
5944: # ---------------- Make a metadata query against the network of library servers
5945:
5946: sub metadata_query {
1.244 matthew 5947: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5948: my %rhash;
1.845 albertel 5949: my %libserv = &all_library();
1.244 matthew 5950: my @server_list = (defined($server_array) ? @$server_array
5951: : keys(%libserv) );
5952: for my $server (@server_list) {
1.118 harris41 5953: unless ($custom or $customshow) {
5954: my $reply=&reply("querysend:".&escape($query),$server);
5955: $rhash{$server}=$reply;
5956: }
5957: else {
5958: my $reply=&reply("querysend:".&escape($query).':'.
5959: &escape($custom).':'.&escape($customshow),
5960: $server);
5961: $rhash{$server}=$reply;
5962: }
1.112 harris41 5963: }
1.118 harris41 5964: return \%rhash;
1.240 www 5965: }
5966:
5967: # ----------------------------------------- Send log queries and wait for reply
5968:
5969: sub log_query {
5970: my ($uname,$udom,$query,%filters)=@_;
5971: my $uhome=&homeserver($uname,$udom);
5972: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5973: my $uhost=&hostname($uhome);
1.800 albertel 5974: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5975: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5976: $uhome);
1.479 albertel 5977: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5978: return get_query_reply($queryid);
5979: }
5980:
1.818 raeburn 5981: # -------------------------- Update MySQL table for portfolio file
5982:
5983: sub update_portfolio_table {
1.821 raeburn 5984: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5985: if ($group ne '') {
5986: $file_name =~s /^\Q$group\E//;
5987: }
1.818 raeburn 5988: my $homeserver = &homeserver($uname,$udom);
5989: my $queryid=
1.821 raeburn 5990: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5991: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5992: my $reply = &get_query_reply($queryid);
5993: return $reply;
5994: }
5995:
1.899 raeburn 5996: # -------------------------- Update MySQL allusers table
5997:
5998: sub update_allusers_table {
5999: my ($uname,$udom,$names) = @_;
6000: my $homeserver = &homeserver($uname,$udom);
6001: my $queryid=
6002: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6003: 'lastname='.&escape($names->{'lastname'}).'%%'.
6004: 'firstname='.&escape($names->{'firstname'}).'%%'.
6005: 'middlename='.&escape($names->{'middlename'}).'%%'.
6006: 'generation='.&escape($names->{'generation'}).'%%'.
6007: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6008: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 6009: return;
1.899 raeburn 6010: }
6011:
1.508 raeburn 6012: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6013:
6014: sub fetch_enrollment_query {
1.511 raeburn 6015: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6016: my $homeserver;
1.547 raeburn 6017: my $maxtries = 1;
1.508 raeburn 6018: if ($context eq 'automated') {
6019: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6020: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6021: } else {
6022: $homeserver = &homeserver($cnum,$dom);
6023: }
1.838 albertel 6024: my $host=&hostname($homeserver);
1.506 raeburn 6025: my $cmd = '';
1.1000 raeburn 6026: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6027: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6028: }
6029: $cmd =~ s/%%$//;
6030: $cmd = &escape($cmd);
6031: my $query = 'fetchenrollment';
1.620 albertel 6032: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6033: unless ($queryid=~/^\Q$host\E\_/) {
6034: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6035: return 'error: '.$queryid;
6036: }
1.506 raeburn 6037: my $reply = &get_query_reply($queryid);
1.547 raeburn 6038: my $tries = 1;
6039: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6040: $reply = &get_query_reply($queryid);
6041: $tries ++;
6042: }
1.526 raeburn 6043: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6044: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6045: } else {
1.901 albertel 6046: my @responses = split(/:/,$reply);
1.515 raeburn 6047: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6048: foreach my $line (@responses) {
6049: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6050: $$replyref{$key} = $value;
6051: }
6052: } else {
1.506 raeburn 6053: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 6054: foreach my $line (@responses) {
6055: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6056: $$replyref{$key} = $value;
6057: if ($value > 0) {
1.800 albertel 6058: foreach my $item (@{$$affiliatesref{$key}}) {
6059: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6060: my $destname = $pathname.'/'.$filename;
6061: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6062: if ($xml_classlist =~ /^error/) {
6063: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6064: } else {
1.506 raeburn 6065: if ( open(FILE,">$destname") ) {
6066: print FILE &unescape($xml_classlist);
6067: close(FILE);
1.526 raeburn 6068: } else {
6069: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6070: }
6071: }
6072: }
6073: }
6074: }
6075: }
6076: return 'ok';
6077: }
6078: return 'error';
6079: }
6080:
1.242 www 6081: sub get_query_reply {
6082: my $queryid=shift;
1.240 www 6083: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6084: my $reply='';
6085: for (1..100) {
6086: sleep 2;
6087: if (-e $replyfile.'.end') {
1.448 albertel 6088: if (open(my $fh,$replyfile)) {
1.904 albertel 6089: $reply = join('',<$fh>);
6090: close($fh);
1.240 www 6091: } else { return 'error: reply_file_error'; }
1.242 www 6092: return &unescape($reply);
6093: }
1.240 www 6094: }
1.242 www 6095: return 'timeout:'.$queryid;
1.240 www 6096: }
6097:
6098: sub courselog_query {
1.241 www 6099: #
6100: # possible filters:
6101: # url: url or symb
6102: # username
6103: # domain
6104: # action: view, submit, grade
6105: # start: timestamp
6106: # end: timestamp
6107: #
1.240 www 6108: my (%filters)=@_;
1.620 albertel 6109: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6110: if ($filters{'url'}) {
6111: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6112: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6113: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6114: }
1.620 albertel 6115: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6116: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6117: return &log_query($cname,$cdom,'courselog',%filters);
6118: }
6119:
6120: sub userlog_query {
1.858 raeburn 6121: #
6122: # possible filters:
6123: # action: log check role
6124: # start: timestamp
6125: # end: timestamp
6126: #
1.240 www 6127: my ($uname,$udom,%filters)=@_;
6128: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6129: }
6130:
1.506 raeburn 6131: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6132:
6133: sub auto_run {
1.508 raeburn 6134: my ($cnum,$cdom) = @_;
1.876 raeburn 6135: my $response = 0;
6136: my $settings;
6137: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6138: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6139: $settings = $domconfig{'autoenroll'};
6140: if ($settings->{'run'} eq '1') {
6141: $response = 1;
6142: }
6143: } else {
1.934 raeburn 6144: my $homeserver;
6145: if (&is_course($cdom,$cnum)) {
6146: $homeserver = &homeserver($cnum,$cdom);
6147: } else {
6148: $homeserver = &domain($cdom,'primary');
6149: }
6150: if ($homeserver ne 'no_host') {
6151: $response = &reply('autorun:'.$cdom,$homeserver);
6152: }
1.876 raeburn 6153: }
1.506 raeburn 6154: return $response;
6155: }
1.776 albertel 6156:
1.506 raeburn 6157: sub auto_get_sections {
1.508 raeburn 6158: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6159: my $homeserver;
6160: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6161: $homeserver = &homeserver($cnum,$cdom);
6162: }
6163: if (!defined($homeserver)) {
6164: if ($cdom =~ /^$match_domain$/) {
6165: $homeserver = &domain($cdom,'primary');
6166: }
6167: }
6168: my @secs;
6169: if (defined($homeserver)) {
6170: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6171: unless ($response eq 'refused') {
6172: @secs = split(/:/,$response);
6173: }
1.506 raeburn 6174: }
6175: return @secs;
6176: }
1.776 albertel 6177:
1.506 raeburn 6178: sub auto_new_course {
1.1056.4.19 raeburn 6179: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6180: my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19 raeburn 6181: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6182: return $response;
6183: }
1.776 albertel 6184:
1.506 raeburn 6185: sub auto_validate_courseID {
1.508 raeburn 6186: my ($cnum,$cdom,$inst_course_id) = @_;
6187: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6188: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6189: return $response;
6190: }
1.776 albertel 6191:
1.1007 raeburn 6192: sub auto_validate_instcode {
1.1020 raeburn 6193: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6194: my ($homeserver,$response);
6195: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6196: $homeserver = &homeserver($cnum,$cdom);
6197: }
6198: if (!defined($homeserver)) {
6199: if ($cdom =~ /^$match_domain$/) {
6200: $homeserver = &domain($cdom,'primary');
6201: }
6202: }
1.1056.4.2 raeburn 6203: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6204: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6205: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6206: return ($outcome,$description);
1.1007 raeburn 6207: }
6208:
1.506 raeburn 6209: sub auto_create_password {
1.873 raeburn 6210: my ($cnum,$cdom,$authparam,$udom) = @_;
6211: my ($homeserver,$response);
1.506 raeburn 6212: my $create_passwd = 0;
6213: my $authchk = '';
1.873 raeburn 6214: if ($udom =~ /^$match_domain$/) {
6215: $homeserver = &domain($udom,'primary');
6216: }
6217: if ($homeserver eq '') {
6218: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6219: $homeserver = &homeserver($cnum,$cdom);
6220: }
6221: }
6222: if ($homeserver eq '') {
6223: $authchk = 'nodomain';
1.506 raeburn 6224: } else {
1.873 raeburn 6225: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6226: if ($response eq 'refused') {
6227: $authchk = 'refused';
6228: } else {
1.901 albertel 6229: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6230: }
1.506 raeburn 6231: }
6232: return ($authparam,$create_passwd,$authchk);
6233: }
6234:
1.706 raeburn 6235: sub auto_photo_permission {
6236: my ($cnum,$cdom,$students) = @_;
6237: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6238: my ($outcome,$perm_reqd,$conditions) =
6239: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6240: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6241: return (undef,undef);
6242: }
1.706 raeburn 6243: return ($outcome,$perm_reqd,$conditions);
6244: }
6245:
6246: sub auto_checkphotos {
6247: my ($uname,$udom,$pid) = @_;
6248: my $homeserver = &homeserver($uname,$udom);
6249: my ($result,$resulttype);
6250: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6251: &escape($uname).':'.&escape($pid),
6252: $homeserver));
1.709 albertel 6253: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6254: return (undef,undef);
6255: }
1.706 raeburn 6256: if ($outcome) {
6257: ($result,$resulttype) = split(/:/,$outcome);
6258: }
6259: return ($result,$resulttype);
6260: }
6261:
6262: sub auto_photochoice {
6263: my ($cnum,$cdom) = @_;
6264: my $homeserver = &homeserver($cnum,$cdom);
6265: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6266: &escape($cdom),
6267: $homeserver)));
1.709 albertel 6268: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6269: return (undef,undef);
6270: }
1.706 raeburn 6271: return ($update,$comment);
6272: }
6273:
6274: sub auto_photoupdate {
6275: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6276: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6277: my $host=&hostname($homeserver);
1.706 raeburn 6278: my $cmd = '';
6279: my $maxtries = 1;
1.800 albertel 6280: foreach my $affiliate (keys(%{$affiliatesref})) {
6281: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6282: }
6283: $cmd =~ s/%%$//;
6284: $cmd = &escape($cmd);
6285: my $query = 'institutionalphotos';
6286: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6287: unless ($queryid=~/^\Q$host\E\_/) {
6288: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6289: return 'error: '.$queryid;
6290: }
6291: my $reply = &get_query_reply($queryid);
6292: my $tries = 1;
6293: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6294: $reply = &get_query_reply($queryid);
6295: $tries ++;
6296: }
6297: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6298: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6299: } else {
6300: my @responses = split(/:/,$reply);
6301: my $outcome = shift(@responses);
6302: foreach my $item (@responses) {
6303: my ($key,$value) = split(/=/,$item);
6304: $$photo{$key} = $value;
6305: }
6306: return $outcome;
6307: }
6308: return 'error';
6309: }
6310:
1.521 raeburn 6311: sub auto_instcode_format {
1.793 albertel 6312: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6313: $cat_order) = @_;
1.521 raeburn 6314: my $courses = '';
1.772 raeburn 6315: my @homeservers;
1.521 raeburn 6316: if ($caller eq 'global') {
1.841 albertel 6317: my %servers = &get_servers($codedom,'library');
6318: foreach my $tryserver (keys(%servers)) {
6319: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6320: push(@homeservers,$tryserver);
6321: }
1.584 raeburn 6322: }
1.1022 raeburn 6323: } elsif ($caller eq 'requests') {
6324: if ($codedom =~ /^$match_domain$/) {
6325: my $chome = &domain($codedom,'primary');
6326: unless ($chome eq 'no_host') {
6327: push(@homeservers,$chome);
6328: }
6329: }
1.521 raeburn 6330: } else {
1.772 raeburn 6331: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6332: }
1.793 albertel 6333: foreach my $code (keys(%{$instcodes})) {
6334: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6335: }
6336: chop($courses);
1.772 raeburn 6337: my $ok_response = 0;
6338: my $response;
6339: while (@homeservers > 0 && $ok_response == 0) {
6340: my $server = shift(@homeservers);
6341: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6342: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6343: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6344: split(/:/,$response);
1.772 raeburn 6345: %{$codes} = (%{$codes},&str2hash($codes_str));
6346: push(@{$codetitles},&str2array($codetitles_str));
6347: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6348: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6349: $ok_response = 1;
6350: }
6351: }
6352: if ($ok_response) {
1.521 raeburn 6353: return 'ok';
1.772 raeburn 6354: } else {
6355: return $response;
1.521 raeburn 6356: }
6357: }
6358:
1.792 raeburn 6359: sub auto_instcode_defaults {
6360: my ($domain,$returnhash,$code_order) = @_;
6361: my @homeservers;
1.841 albertel 6362:
6363: my %servers = &get_servers($domain,'library');
6364: foreach my $tryserver (keys(%servers)) {
6365: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6366: push(@homeservers,$tryserver);
6367: }
1.792 raeburn 6368: }
1.841 albertel 6369:
1.792 raeburn 6370: my $response;
1.841 albertel 6371: foreach my $server (@homeservers) {
1.792 raeburn 6372: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6373: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6374:
6375: foreach my $pair (split(/\&/,$response)) {
6376: my ($name,$value)=split(/\=/,$pair);
6377: if ($name eq 'code_order') {
6378: @{$code_order} = split(/\&/,&unescape($value));
6379: } else {
6380: $returnhash->{&unescape($name)}=&unescape($value);
6381: }
6382: }
6383: return 'ok';
1.792 raeburn 6384: }
1.841 albertel 6385:
6386: return $response;
1.1003 raeburn 6387: }
6388:
6389: sub auto_possible_instcodes {
1.1007 raeburn 6390: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6391: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6392: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6393: return;
6394: }
1.1003 raeburn 6395: my (@homeservers,$uhome);
6396: if (defined(&domain($domain,'primary'))) {
6397: $uhome=&domain($domain,'primary');
6398: push(@homeservers,&domain($domain,'primary'));
6399: } else {
6400: my %servers = &get_servers($domain,'library');
6401: foreach my $tryserver (keys(%servers)) {
6402: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6403: push(@homeservers,$tryserver);
6404: }
6405: }
6406: }
6407: my $response;
6408: foreach my $server (@homeservers) {
6409: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6410: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6411: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6412: split(':',$response);
6413: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6414: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6415: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6416: my ($name,$value)=split('=',$item);
6417: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6418: }
6419: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6420: my ($name,$value)=split('=',$item);
6421: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6422: }
6423: return 'ok';
6424: }
6425: return $response;
6426: }
1.792 raeburn 6427:
1.1010 raeburn 6428: sub auto_courserequest_checks {
6429: my ($dom) = @_;
1.1020 raeburn 6430: my ($homeserver,%validations);
6431: if ($dom =~ /^$match_domain$/) {
6432: $homeserver = &domain($dom,'primary');
6433: }
6434: unless ($homeserver eq 'no_host') {
6435: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6436: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6437: my @items = split(/&/,$response);
6438: foreach my $item (@items) {
6439: my ($key,$value) = split('=',$item);
6440: $validations{&unescape($key)} = &thaw_unescape($value);
6441: }
6442: }
6443: }
1.1010 raeburn 6444: return %validations;
6445: }
6446:
1.1020 raeburn 6447: sub auto_courserequest_validation {
6448: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6449: my ($homeserver,$response);
6450: if ($dom =~ /^$match_domain$/) {
6451: $homeserver = &domain($dom,'primary');
6452: }
6453: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6454:
1.1020 raeburn 6455: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6456: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6457: ':'.&escape($instcode).':'.&escape($instseclist),
6458: $homeserver));
6459: }
6460: return $response;
6461: }
6462:
1.777 albertel 6463: sub auto_validate_class_sec {
1.918 raeburn 6464: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6465: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6466: my $ownerlist;
6467: if (ref($owners) eq 'ARRAY') {
6468: $ownerlist = join(',',@{$owners});
6469: } else {
6470: $ownerlist = $owners;
6471: }
1.773 raeburn 6472: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6473: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6474: return $response;
6475: }
6476:
1.679 raeburn 6477: # ------------------------------------------------------- Course Group routines
6478:
6479: sub get_coursegroups {
1.809 raeburn 6480: my ($cdom,$cnum,$group,$namespace) = @_;
6481: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6482: }
6483:
1.679 raeburn 6484: sub modify_coursegroup {
6485: my ($cdom,$cnum,$groupsettings) = @_;
6486: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6487: }
6488:
1.809 raeburn 6489: sub toggle_coursegroup_status {
6490: my ($cdom,$cnum,$group,$action) = @_;
6491: my ($from_namespace,$to_namespace);
6492: if ($action eq 'delete') {
6493: $from_namespace = 'coursegroups';
6494: $to_namespace = 'deleted_groups';
6495: } else {
6496: $from_namespace = 'deleted_groups';
6497: $to_namespace = 'coursegroups';
6498: }
6499: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6500: if (my $tmp = &error(%curr_group)) {
6501: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6502: return ('read error',$tmp);
6503: } else {
6504: my %savedsettings = %curr_group;
1.809 raeburn 6505: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6506: my $deloutcome;
6507: if ($result eq 'ok') {
1.809 raeburn 6508: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6509: } else {
6510: return ('write error',$result);
6511: }
6512: if ($deloutcome eq 'ok') {
6513: return 'ok';
6514: } else {
6515: return ('delete error',$deloutcome);
6516: }
6517: }
6518: }
6519:
1.679 raeburn 6520: sub modify_group_roles {
1.957 raeburn 6521: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6522: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6523: my $role = 'gr/'.&escape($userprivs);
6524: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6525: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6526: if ($result eq 'ok') {
6527: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6528: }
1.679 raeburn 6529: return $result;
6530: }
6531:
6532: sub modify_coursegroup_membership {
6533: my ($cdom,$cnum,$membership) = @_;
6534: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6535: return $result;
6536: }
6537:
1.682 raeburn 6538: sub get_active_groups {
6539: my ($udom,$uname,$cdom,$cnum) = @_;
6540: my $now = time;
6541: my %groups = ();
6542: foreach my $key (keys(%env)) {
1.811 albertel 6543: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6544: my ($start,$end) = split(/\./,$env{$key});
6545: if (($end!=0) && ($end<$now)) { next; }
6546: if (($start!=0) && ($start>$now)) { next; }
6547: if ($1 eq $cdom && $2 eq $cnum) {
6548: $groups{$3} = $env{$key} ;
6549: }
6550: }
6551: }
6552: return %groups;
6553: }
6554:
1.683 raeburn 6555: sub get_group_membership {
6556: my ($cdom,$cnum,$group) = @_;
6557: return(&dump('groupmembership',$cdom,$cnum,$group));
6558: }
6559:
6560: sub get_users_groups {
6561: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6562: my @usersgroups;
1.683 raeburn 6563: my $cachetime=1800;
6564:
6565: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6566: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6567: if (defined($cached)) {
1.734 albertel 6568: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6569: } else {
6570: $grouplist = '';
1.816 raeburn 6571: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6572: my $extra = &freeze_escape({'skipcheck' => 1});
6573: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6574: my $access_end = $env{'course.'.$courseid.
6575: '.default_enrollment_end_date'};
6576: my $now = time;
6577: foreach my $key (keys(%roleshash)) {
6578: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6579: my $group = $1;
6580: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6581: my $start = $2;
6582: my $end = $1;
6583: if ($start == -1) { next; } # deleted from group
6584: if (($start!=0) && ($start>$now)) { next; }
6585: if (($end!=0) && ($end<$now)) {
6586: if ($access_end && $access_end < $now) {
6587: if ($access_end - $end < 86400) {
6588: push(@usersgroups,$group);
1.733 raeburn 6589: }
6590: }
1.817 raeburn 6591: next;
1.733 raeburn 6592: }
1.817 raeburn 6593: push(@usersgroups,$group);
1.683 raeburn 6594: }
6595: }
6596: }
1.817 raeburn 6597: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6598: $grouplist = join(':',@usersgroups);
6599: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6600: }
1.733 raeburn 6601: return @usersgroups;
1.683 raeburn 6602: }
6603:
6604: sub devalidate_getgroups_cache {
6605: my ($udom,$uname,$cdom,$cnum)=@_;
6606: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6607:
1.683 raeburn 6608: my $hashid="$udom:$uname:$courseid";
6609: &devalidate_cache_new('getgroups',$hashid);
6610: }
6611:
1.12 www 6612: # ------------------------------------------------------------------ Plain Text
6613:
6614: sub plaintext {
1.988 raeburn 6615: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6616: if ($short =~ m{^cr/}) {
1.758 albertel 6617: return (split('/',$short))[-1];
6618: }
1.742 raeburn 6619: if (!defined($cid)) {
6620: $cid = $env{'request.course.id'};
6621: }
6622: my %rolenames = (
1.1008 raeburn 6623: Course => 'std',
6624: Community => 'alt1',
1.742 raeburn 6625: );
1.1037 raeburn 6626: if ($cid ne '') {
6627: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6628: unless ($forcedefault) {
6629: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6630: &Apache::lonlocal::mt_escape(\$roletext);
6631: return &Apache::lonlocal::mt($roletext);
6632: }
6633: }
6634: }
6635: if ((defined($type)) && (defined($rolenames{$type})) &&
6636: (defined($rolenames{$type})) &&
6637: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6638: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6639: } elsif ($cid ne '') {
6640: my $crstype = $env{'course.'.$cid.'.type'};
6641: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6642: (defined($prp{$short}{$rolenames{$crstype}}))) {
6643: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6644: }
1.742 raeburn 6645: }
1.1037 raeburn 6646: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6647: }
6648:
6649: # ----------------------------------------------------------------- Assign Role
6650:
6651: sub assignrole {
1.957 raeburn 6652: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6653: $context)=@_;
1.21 www 6654: my $mrole;
6655: if ($role =~ /^cr\//) {
1.393 www 6656: my $cwosec=$url;
1.811 albertel 6657: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6658: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6659: my $refused = 1;
6660: if ($context eq 'requestcourses') {
6661: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6662: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6663: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6664: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6665: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6666: if ($crsenv{'internal.courseowner'} eq
6667: $env{'user.name'}.':'.$env{'user.domain'}) {
6668: $refused = '';
6669: }
6670: }
6671: }
6672: }
6673: }
6674: if ($refused) {
6675: &logthis('Refused custom assignrole: '.
6676: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6677: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6678: return 'refused';
6679: }
1.104 www 6680: }
1.21 www 6681: $mrole='cr';
1.678 raeburn 6682: } elsif ($role =~ /^gr\//) {
6683: my $cwogrp=$url;
1.811 albertel 6684: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6685: unless (&allowed('mdg',$cwogrp)) {
6686: &logthis('Refused group assignrole: '.
6687: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6688: $env{'user.name'}.' at '.$env{'user.domain'});
6689: return 'refused';
6690: }
6691: $mrole='gr';
1.21 www 6692: } else {
1.82 www 6693: my $cwosec=$url;
1.811 albertel 6694: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6695: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6696: my $refused;
6697: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6698: if (!(&allowed('c'.$role,$url))) {
6699: $refused = 1;
6700: }
6701: } else {
6702: $refused = 1;
6703: }
1.947 raeburn 6704: if ($refused) {
1.1045 raeburn 6705: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6706: if (!$selfenroll && $context eq 'course') {
6707: my %crsenv;
6708: if ($role eq 'cc' || $role eq 'co') {
6709: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6710: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6711: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6712: if ($crsenv{'internal.courseowner'} eq
6713: $env{'user.name'}.':'.$env{'user.domain'}) {
6714: $refused = '';
6715: }
6716: }
6717: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6718: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6719: if ($crsenv{'internal.courseowner'} eq
6720: $env{'user.name'}.':'.$env{'user.domain'}) {
6721: $refused = '';
6722: }
6723: }
6724: }
6725: }
6726: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6727: $refused = '';
1.1017 raeburn 6728: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6729: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6730: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6731: my $wrongcc;
6732: if ($cnum =~ /^$match_community$/) {
6733: $wrongcc = 1 if ($role eq 'cc');
6734: } else {
6735: $wrongcc = 1 if ($role eq 'co');
6736: }
6737: unless ($wrongcc) {
6738: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6739: if ($crsenv{'internal.courseowner'} eq
6740: $env{'user.name'}.':'.$env{'user.domain'}) {
6741: $refused = '';
6742: }
1.1017 raeburn 6743: }
6744: }
6745: }
6746: if ($refused) {
1.947 raeburn 6747: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6748: ' '.$role.' '.$end.' '.$start.' by '.
6749: $env{'user.name'}.' at '.$env{'user.domain'});
6750: return 'refused';
6751: }
1.932 raeburn 6752: }
1.1056.4.30 raeburn 6753: } elsif ($role eq 'au') {
6754: if ($url ne '/'.$udom.'/') {
6755: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
6756: ' to assign author role for '.$uname.':'.$udom.
6757: ' in domain: '.$url.' refused (wrong domain).');
6758: return 'refused';
6759: }
1.104 www 6760: }
1.21 www 6761: $mrole=$role;
6762: }
1.620 albertel 6763: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6764: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6765: if ($end) { $command.='_'.$end; }
1.21 www 6766: if ($start) {
6767: if ($end) {
1.81 www 6768: $command.='_'.$start;
1.21 www 6769: } else {
1.81 www 6770: $command.='_0_'.$start;
1.21 www 6771: }
6772: }
1.739 raeburn 6773: my $origstart = $start;
6774: my $origend = $end;
1.957 raeburn 6775: my $delflag;
1.357 www 6776: # actually delete
6777: if ($deleteflag) {
1.373 www 6778: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6779: # modify command to delete the role
1.620 albertel 6780: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6781: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6782: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6783: # set start and finish to negative values for userrolelog
6784: $start=-1;
6785: $end=-1;
1.957 raeburn 6786: $delflag = 1;
1.357 www 6787: }
6788: }
6789: # send command
1.349 www 6790: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6791: # log new user role if status is ok
1.349 www 6792: if ($answer eq 'ok') {
1.663 raeburn 6793: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6794: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6795: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6796: unless ($role =~ /^gr/) {
6797: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6798: $origstart,$selfenroll,$context);
1.739 raeburn 6799: }
1.1053 raeburn 6800: if ($role eq 'cc') {
6801: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6802: }
1.349 www 6803: }
6804: return $answer;
1.169 harris41 6805: }
6806:
1.1053 raeburn 6807: sub autoupdate_coowners {
6808: my ($url,$end,$start,$uname,$udom) = @_;
6809: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6810: if (($cdom ne '') && ($cnum ne '')) {
6811: my $now = time;
6812: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6813: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6814: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6815: my $instcode = $coursehash{'internal.coursecode'};
6816: if ($instcode ne '') {
1.1056 raeburn 6817: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6818: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6819: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6820: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6821: if ($result eq 'valid') {
6822: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6823: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6824: push(@newcoowners,$coowner);
6825: }
6826: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6827: push(@newcoowners,$uname.':'.$udom);
6828: }
6829: @newcoowners = sort(@newcoowners);
6830: } else {
6831: push(@newcoowners,$uname.':'.$udom);
6832: }
6833: } else {
6834: if ($coursehash{'internal.co-owners'}) {
6835: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6836: unless ($coowner eq $uname.':'.$udom) {
6837: push(@newcoowners,$coowner);
6838: }
6839: }
6840: unless (@newcoowners > 0) {
6841: $delcoowners = 1;
6842: $coowners = '';
6843: }
6844: }
6845: }
6846: if (@newcoowners || $delcoowners) {
6847: &store_coowners($cdom,$cnum,$coursehash{'home'},
6848: $delcoowners,@newcoowners);
6849: }
6850: }
6851: }
6852: }
6853: }
6854: }
6855: }
6856:
6857: sub store_coowners {
6858: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6859: my $cid = $cdom.'_'.$cnum;
6860: my ($coowners,$delresult,$putresult);
6861: if (@newcoowners) {
6862: $coowners = join(',',@newcoowners);
6863: my %coownershash = (
6864: 'internal.co-owners' => $coowners,
6865: );
6866: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6867: if ($putresult eq 'ok') {
6868: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6869: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6870: }
6871: }
6872: }
6873: if ($delcoowners) {
6874: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6875: if ($delresult eq 'ok') {
6876: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6877: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6878: }
6879: }
6880: }
6881: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6882: my %crsinfo =
6883: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6884: if (ref($crsinfo{$cid}) eq 'HASH') {
6885: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6886: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6887: }
6888: }
6889: }
6890:
1.169 harris41 6891: # -------------------------------------------------- Modify user authentication
1.197 www 6892: # Overrides without validation
6893:
1.169 harris41 6894: sub modifyuserauth {
6895: my ($udom,$uname,$umode,$upass)=@_;
6896: my $uhome=&homeserver($uname,$udom);
1.197 www 6897: unless (&allowed('mau',$udom)) { return 'refused'; }
6898: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6899: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6900: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6901: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6902: &escape($upass),$uhome);
1.620 albertel 6903: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6904: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6905: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6906: &log($udom,,$uname,$uhome,
1.620 albertel 6907: 'Authentication changed by '.$env{'user.domain'}.', '.
6908: $env{'user.name'}.', '.$umode.
1.197 www 6909: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6910: unless ($reply eq 'ok') {
1.197 www 6911: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6912: return 'error: '.$reply;
6913: }
1.170 harris41 6914: return 'ok';
1.80 www 6915: }
6916:
1.81 www 6917: # --------------------------------------------------------------- Modify a user
1.80 www 6918:
1.81 www 6919: sub modifyuser {
1.206 matthew 6920: my ($udom, $uname, $uid,
6921: $umode, $upass, $first,
6922: $middle, $last, $gene,
1.1056.4.1 raeburn 6923: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6924: $udom= &LONCAPA::clean_domain($udom);
6925: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6926: my $showcandelete = 'none';
6927: if (ref($candelete) eq 'ARRAY') {
6928: if (@{$candelete} > 0) {
6929: $showcandelete = join(', ',@{$candelete});
6930: }
6931: }
1.81 www 6932: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6933: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6934: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6935: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6936: ' desiredhome not specified').
1.620 albertel 6937: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6938: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6939: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6940: my $newuser;
6941: if ($uhome eq 'no_host') {
6942: $newuser = 1;
6943: }
1.80 www 6944: # ----------------------------------------------------------------- Create User
1.406 albertel 6945: if (($uhome eq 'no_host') &&
6946: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6947: my $unhome='';
1.844 albertel 6948: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6949: $unhome = $desiredhome;
1.620 albertel 6950: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6951: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6952: } else { # load balancing routine for determining $unhome
1.81 www 6953: my $loadm=10000000;
1.841 albertel 6954: my %servers = &get_servers($udom,'library');
6955: foreach my $tryserver (keys(%servers)) {
6956: my $answer=reply('load',$tryserver);
6957: if (($answer=~/\d+/) && ($answer<$loadm)) {
6958: $loadm=$answer;
6959: $unhome=$tryserver;
6960: }
1.80 www 6961: }
6962: }
6963: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6964: return 'error: unable to find a home server for '.$uname.
6965: ' in domain '.$udom;
1.80 www 6966: }
6967: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6968: &escape($upass),$unhome);
6969: unless ($reply eq 'ok') {
6970: return 'error: '.$reply;
6971: }
1.230 stredwic 6972: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6973: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6974: return 'error: unable verify users home machine.';
1.80 www 6975: }
1.209 matthew 6976: } # End of creation of new user
1.80 www 6977: # ---------------------------------------------------------------------- Add ID
6978: if ($uid) {
6979: $uid=~tr/A-Z/a-z/;
6980: my %uidhash=&idrget($udom,$uname);
1.196 www 6981: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6982: && (!$forceid)) {
1.80 www 6983: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6984: return 'error: user id "'.$uid.'" does not match '.
6985: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6986: }
6987: } else {
6988: &idput($udom,($uname => $uid));
6989: }
6990: }
6991: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6992: my @tmp=&get('environment',
1.899 raeburn 6993: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6994: 'permanentemail','inststatus'],
1.134 albertel 6995: $udom,$uname);
1.1056.4.4 raeburn 6996: my (%names,%oldnames);
1.313 matthew 6997: if ($tmp[0] =~ m/^error:.*/) {
6998: %names=();
6999: } else {
7000: %names = @tmp;
1.1056.4.4 raeburn 7001: %oldnames = %names;
1.313 matthew 7002: }
1.1056.4.6 raeburn 7003: #
1.1056.4.1 raeburn 7004: # If name, email and/or uid are blank (e.g., because an uploaded file
7005: # of users did not contain them), do not overwrite existing values
7006: # unless field is in $candelete array ref.
7007: #
7008:
7009: my @fields = ('firstname','middlename','lastname','generation',
7010: 'permanentemail','id');
7011: my %newvalues;
7012: if (ref($candelete) eq 'ARRAY') {
7013: foreach my $field (@fields) {
7014: if (grep(/^\Q$field\E$/,@{$candelete})) {
7015: if ($field eq 'firstname') {
7016: $names{$field} = $first;
7017: } elsif ($field eq 'middlename') {
7018: $names{$field} = $middle;
7019: } elsif ($field eq 'lastname') {
7020: $names{$field} = $last;
7021: } elsif ($field eq 'generation') {
7022: $names{$field} = $gene;
7023: } elsif ($field eq 'permanentemail') {
7024: $names{$field} = $email;
7025: } elsif ($field eq 'id') {
7026: $names{$field} = $uid;
7027: }
7028: }
7029: }
7030: }
1.388 www 7031: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7032: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7033: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7034: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7035: if ($email) {
7036: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7037: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7038: }
1.899 raeburn 7039: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7040: if (defined($inststatus)) {
7041: $names{'inststatus'} = '';
7042: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7043: if (ref($usertypes) eq 'HASH') {
7044: my @okstatuses;
7045: foreach my $item (split(/:/,$inststatus)) {
7046: if (defined($usertypes->{$item})) {
7047: push(@okstatuses,$item);
7048: }
7049: }
7050: if (@okstatuses) {
7051: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7052: }
7053: }
7054: }
1.1056.4.4 raeburn 7055: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7056: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 7057: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7058: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7059: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7060: } else {
7061: $logmsg .= ' during self creation';
7062: }
1.1056.4.4 raeburn 7063: my $changed;
7064: if ($newuser) {
7065: $changed = 1;
7066: } else {
7067: foreach my $field (@fields) {
7068: if ($names{$field} ne $oldnames{$field}) {
7069: $changed = 1;
7070: last;
7071: }
7072: }
7073: }
7074: unless ($changed) {
7075: $logmsg = 'No changes in user information needed for: '.$logmsg;
7076: &logthis($logmsg);
7077: return 'ok';
7078: }
7079: my $reply = &put('environment', \%names, $udom,$uname);
7080: if ($reply ne 'ok') {
7081: return 'error: '.$reply;
7082: }
1.1056.4.11 raeburn 7083: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7084: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7085: }
1.1056.4.4 raeburn 7086: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7087: &devalidate_cache_new('namescache',$uname.':'.$udom);
7088: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7089: &logthis($logmsg);
1.134 albertel 7090: return 'ok';
1.80 www 7091: }
7092:
1.81 www 7093: # -------------------------------------------------------------- Modify student
1.80 www 7094:
1.81 www 7095: sub modifystudent {
7096: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7097: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7098: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7099: if (!$cid) {
1.620 albertel 7100: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7101: return 'not_in_class';
7102: }
1.80 www 7103: }
7104: # --------------------------------------------------------------- Make the user
1.81 www 7105: my $reply=&modifyuser
1.209 matthew 7106: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7107: $desiredhome,$email,$inststatus);
1.80 www 7108: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7109: # This will cause &modify_student_enrollment to get the uid from the
7110: # students environment
7111: $uid = undef if (!$forceid);
1.455 albertel 7112: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7113: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7114: return $reply;
7115: }
7116:
7117: sub modify_student_enrollment {
1.957 raeburn 7118: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7119: my ($cdom,$cnum,$chome);
7120: if (!$cid) {
1.620 albertel 7121: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7122: return 'not_in_class';
7123: }
1.620 albertel 7124: $cdom=$env{'course.'.$cid.'.domain'};
7125: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7126: } else {
7127: ($cdom,$cnum)=split(/_/,$cid);
7128: }
1.620 albertel 7129: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7130: if (!$chome) {
1.457 raeburn 7131: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7132: }
1.455 albertel 7133: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7134: # Make sure the user exists
1.81 www 7135: my $uhome=&homeserver($uname,$udom);
7136: if (($uhome eq '') || ($uhome eq 'no_host')) {
7137: return 'error: no such user';
7138: }
1.297 matthew 7139: # Get student data if we were not given enough information
7140: if (!defined($first) || $first eq '' ||
7141: !defined($last) || $last eq '' ||
7142: !defined($uid) || $uid eq '' ||
7143: !defined($middle) || $middle eq '' ||
7144: !defined($gene) || $gene eq '') {
1.294 matthew 7145: # They did not supply us with enough data to enroll the student, so
7146: # we need to pick up more information.
1.297 matthew 7147: my %tmp = &get('environment',
1.294 matthew 7148: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7149: ,$udom,$uname);
7150:
1.800 albertel 7151: #foreach my $key (keys(%tmp)) {
7152: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7153: #}
1.294 matthew 7154: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7155: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7156: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7157: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7158: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7159: }
1.556 albertel 7160: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7161: my $reply=cput('classlist',
7162: {"$uname:$udom" =>
1.515 raeburn 7163: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7164: $cdom,$cnum);
1.81 www 7165: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7166: return 'error: '.$reply;
1.652 albertel 7167: } else {
7168: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7169: }
1.297 matthew 7170: # Add student role to user
1.83 www 7171: my $uurl='/'.$cid;
1.81 www 7172: $uurl=~s/\_/\//g;
7173: if ($usec) {
7174: $uurl.='/'.$usec;
7175: }
1.957 raeburn 7176: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7177: }
7178:
1.556 albertel 7179: sub format_name {
7180: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7181: my $name;
7182: if ($first ne 'lastname') {
7183: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7184: } else {
7185: if ($lastname=~/\S/) {
7186: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7187: $name=~s/\s+,/,/;
7188: } else {
7189: $name.= $firstname.' '.$middlename.' '.$generation;
7190: }
7191: }
7192: $name=~s/^\s+//;
7193: $name=~s/\s+$//;
7194: $name=~s/\s+/ /g;
7195: return $name;
7196: }
7197:
1.84 www 7198: # ------------------------------------------------- Write to course preferences
7199:
7200: sub writecoursepref {
7201: my ($courseid,%prefs)=@_;
7202: $courseid=~s/^\///;
7203: $courseid=~s/\_/\//g;
7204: my ($cdomain,$cnum)=split(/\//,$courseid);
7205: my $chome=homeserver($cnum,$cdomain);
7206: if (($chome eq '') || ($chome eq 'no_host')) {
7207: return 'error: no such course';
7208: }
7209: my $cstring='';
1.800 albertel 7210: foreach my $pref (keys(%prefs)) {
7211: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7212: }
1.84 www 7213: $cstring=~s/\&$//;
7214: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7215: }
7216:
7217: # ---------------------------------------------------------- Make/modify course
7218:
7219: sub createcourse {
1.741 raeburn 7220: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7221: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7222: $url=&declutter($url);
7223: my $cid='';
1.1028 raeburn 7224: if ($context eq 'requestcourses') {
7225: my $can_create = 0;
7226: my ($ownername,$ownerdom) = split(':',$course_owner);
7227: if ($udom eq $ownerdom) {
7228: if (&usertools_access($ownername,$ownerdom,$category,undef,
7229: $context)) {
7230: $can_create = 1;
7231: }
7232: } else {
7233: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7234: $category);
7235: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7236: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7237: if (@curr > 0) {
7238: my @options = qw(approval validate autolimit);
7239: my $optregex = join('|',@options);
7240: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7241: $can_create = 1;
7242: }
7243: }
7244: }
7245: }
7246: if ($can_create) {
7247: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7248: unless (&allowed('ccc',$udom)) {
7249: return 'refused';
7250: }
1.1017 raeburn 7251: }
7252: } else {
7253: return 'refused';
7254: }
1.1028 raeburn 7255: } elsif (!&allowed('ccc',$udom)) {
7256: return 'refused';
1.84 www 7257: }
1.1011 raeburn 7258: # --------------------------------------------------------------- Get Unique ID
7259: my $uname;
7260: if ($cnum =~ /^$match_courseid$/) {
7261: my $chome=&homeserver($cnum,$udom,'true');
7262: if (($chome eq '') || ($chome eq 'no_host')) {
7263: $uname = $cnum;
7264: } else {
1.1038 raeburn 7265: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7266: }
7267: } else {
1.1038 raeburn 7268: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7269: }
7270: return $uname if ($uname =~ /^error/);
7271: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7272: if (!defined($course_server)) {
7273: if (defined(&domain($udom,'primary'))) {
7274: $course_server = &domain($udom,'primary');
7275: } else {
7276: $course_server = $env{'user.home'};
7277: }
7278: }
7279: my %host_servers =
7280: &Apache::lonnet::get_servers($udom,'library');
7281: unless ($host_servers{$course_server}) {
7282: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7283: }
1.84 www 7284: # ------------------------------------------------------------- Make the course
7285: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7286: $course_server);
1.84 www 7287: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7288: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7289: if (($uhome eq '') || ($uhome eq 'no_host')) {
7290: return 'error: no such course';
7291: }
1.271 www 7292: # ----------------------------------------------------------------- Course made
1.516 raeburn 7293: # log existence
1.1029 raeburn 7294: my $now = time;
1.918 raeburn 7295: my $newcourse = {
7296: $udom.'_'.$uname => {
1.921 raeburn 7297: description => $description,
7298: inst_code => $inst_code,
7299: owner => $course_owner,
7300: type => $crstype,
1.1029 raeburn 7301: creator => $env{'user.name'}.':'.
7302: $env{'user.domain'},
7303: created => $now,
7304: context => $context,
1.918 raeburn 7305: },
7306: };
1.921 raeburn 7307: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7308: # set toplevel url
1.271 www 7309: my $topurl=$url;
7310: unless ($nonstandard) {
7311: # ------------------------------------------ For standard courses, make top url
7312: my $mapurl=&clutter($url);
1.278 www 7313: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7314: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7315: <map>
7316: <resource id="1" type="start"></resource>
7317: <resource id="2" src="$mapurl"></resource>
7318: <resource id="3" type="finish"></resource>
7319: <link index="1" from="1" to="2"></link>
7320: <link index="2" from="2" to="3"></link>
7321: </map>
7322: ENDINITMAP
7323: $topurl=&declutter(
1.638 albertel 7324: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7325: );
7326: }
7327: # ----------------------------------------------------------- Write preferences
1.84 www 7328: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7329: ('description' => $description,
7330: 'url' => $topurl,
7331: 'internal.creator' => $env{'user.name'}.':'.
7332: $env{'user.domain'},
7333: 'internal.created' => $now,
7334: 'internal.creationcontext' => $context)
7335: );
1.84 www 7336: return '/'.$udom.'/'.$uname;
7337: }
7338:
1.1011 raeburn 7339: # ------------------------------------------------------------------- Create ID
7340: sub generate_coursenum {
1.1038 raeburn 7341: my ($udom,$crstype) = @_;
1.1011 raeburn 7342: my $domdesc = &domain($udom);
7343: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7344: my $first;
7345: if ($crstype eq 'Community') {
7346: $first = '0';
7347: } else {
7348: $first = int(1+rand(9));
7349: }
7350: my $uname=$first.
1.1011 raeburn 7351: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7352: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7353: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7354: # ----------------------------------------------- Make sure that does not exist
7355: my $uhome=&homeserver($uname,$udom,'true');
7356: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7357: if ($crstype eq 'Community') {
7358: $first = '0';
7359: } else {
7360: $first = int(1+rand(9));
7361: }
7362: $uname=$first.
1.1011 raeburn 7363: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7364: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7365: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7366: $uhome=&homeserver($uname,$udom,'true');
7367: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7368: return 'error: unable to generate unique course-ID';
7369: }
7370: }
7371: return $uname;
7372: }
7373:
1.813 albertel 7374: sub is_course {
7375: my ($cdom,$cnum) = @_;
7376: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7377: undef,'.');
1.813 albertel 7378: if (exists($courses{$cdom.'_'.$cnum})) {
7379: return 1;
7380: }
7381: return 0;
7382: }
7383:
1.1015 raeburn 7384: sub store_userdata {
7385: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7386: my $result;
1.1016 raeburn 7387: if ($datakey ne '') {
1.1013 raeburn 7388: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7389: if ($udom eq '' || $uname eq '') {
7390: $udom = $env{'user.domain'};
7391: $uname = $env{'user.name'};
7392: }
7393: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7394: if (($uhome eq '') || ($uhome eq 'no_host')) {
7395: $result = 'error: no_host';
7396: } else {
7397: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7398: $storehash->{'host'} = $perlvar{'lonHostID'};
7399:
7400: my $namevalue='';
7401: foreach my $key (keys(%{$storehash})) {
7402: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7403: }
7404: $namevalue=~s/\&$//;
1.1056.4.24 raeburn 7405: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7406: $namevalue,$uhome);
1.1013 raeburn 7407: }
7408: } else {
7409: $result = 'error: data to store was not a hash reference';
7410: }
7411: } else {
7412: $result= 'error: invalid requestkey';
7413: }
7414: return $result;
7415: }
7416:
1.21 www 7417: # ---------------------------------------------------------- Assign Custom Role
7418:
7419: sub assigncustomrole {
1.957 raeburn 7420: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7421: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7422: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7423: }
7424:
7425: # ----------------------------------------------------------------- Revoke Role
7426:
7427: sub revokerole {
1.957 raeburn 7428: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7429: my $now=time;
1.965 raeburn 7430: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7431: }
7432:
7433: # ---------------------------------------------------------- Revoke Custom Role
7434:
7435: sub revokecustomrole {
1.957 raeburn 7436: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7437: my $now=time;
1.357 www 7438: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7439: $deleteflag,$selfenroll,$context);
1.17 www 7440: }
7441:
1.533 banghart 7442: # ------------------------------------------------------------ Disk usage
1.535 albertel 7443: sub diskusage {
1.955 raeburn 7444: my ($udom,$uname,$directorypath,$getpropath)=@_;
7445: $directorypath =~ s/\/$//;
7446: my $listing=&reply('du2:'.&escape($directorypath).':'
7447: .&escape($getpropath).':'.&escape($uname).':'
7448: .&escape($udom),homeserver($uname,$udom));
7449: if ($listing eq 'unknown_cmd') {
7450: if ($getpropath) {
7451: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7452: }
7453: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7454: }
1.514 albertel 7455: return $listing;
1.512 banghart 7456: }
7457:
1.566 banghart 7458: sub is_locked {
1.1056.4.17 raeburn 7459: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7460: my @check;
7461: my $is_locked;
1.1056.4.14 raeburn 7462: push(@check,$file_name);
1.613 albertel 7463: my %locked = &get('file_permissions',\@check,
1.620 albertel 7464: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7465: my ($tmp)=keys(%locked);
7466: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7467:
1.566 banghart 7468: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7469: $is_locked = 'false';
7470: foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17 raeburn 7471: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7472: $is_locked = 'true';
1.1056.4.17 raeburn 7473: if (ref($which) eq 'ARRAY') {
7474: push(@{$which},$entry);
7475: } else {
7476: last;
7477: }
1.745 raeburn 7478: }
7479: }
1.566 banghart 7480: } else {
7481: $is_locked = 'false';
7482: }
1.1056.4.14 raeburn 7483: return $is_locked;
1.566 banghart 7484: }
7485:
1.759 albertel 7486: sub declutter_portfile {
7487: my ($file) = @_;
1.833 albertel 7488: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7489: return $file;
7490: }
7491:
1.559 banghart 7492: # ------------------------------------------------------------- Mark as Read Only
7493:
7494: sub mark_as_readonly {
7495: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7496: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7497: my ($tmp)=keys(%current_permissions);
7498: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7499: foreach my $file (@{$files}) {
1.759 albertel 7500: $file = &declutter_portfile($file);
1.561 banghart 7501: push(@{$current_permissions{$file}},$what);
1.559 banghart 7502: }
1.613 albertel 7503: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7504: return;
7505: }
7506:
1.572 banghart 7507: # ------------------------------------------------------------Save Selected Files
7508:
7509: sub save_selected_files {
7510: my ($user, $path, @files) = @_;
7511: my $filename = $user."savedfiles";
1.573 banghart 7512: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7513: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7514: foreach my $file (@files) {
1.620 albertel 7515: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7516: }
7517: foreach my $file (@other_files) {
1.574 banghart 7518: print (OUT $file."\n");
1.572 banghart 7519: }
1.574 banghart 7520: close (OUT);
1.572 banghart 7521: return 'ok';
7522: }
7523:
1.574 banghart 7524: sub clear_selected_files {
7525: my ($user) = @_;
7526: my $filename = $user."savedfiles";
7527: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7528: print (OUT undef);
7529: close (OUT);
7530: return ("ok");
7531: }
7532:
1.572 banghart 7533: sub files_in_path {
7534: my ($user, $path) = @_;
7535: my $filename = $user."savedfiles";
7536: my %return_files;
1.574 banghart 7537: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7538: while (my $line_in = <IN>) {
1.574 banghart 7539: chomp ($line_in);
7540: my @paths_and_file = split (m!/!, $line_in);
7541: my $file_part = pop (@paths_and_file);
7542: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7543: $path_part.='/';
7544: my $path_and_file = $path_part.$file_part;
7545: if ($path_part eq $path) {
7546: $return_files{$file_part}= 'selected';
7547: }
7548: }
1.574 banghart 7549: close (IN);
7550: return (\%return_files);
1.572 banghart 7551: }
7552:
7553: # called in portfolio select mode, to show files selected NOT in current directory
7554: sub files_not_in_path {
7555: my ($user, $path) = @_;
7556: my $filename = $user."savedfiles";
7557: my @return_files;
7558: my $path_part;
1.800 albertel 7559: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7560: while (my $line = <IN>) {
1.572 banghart 7561: #ok, I know it's clunky, but I want it to work
1.800 albertel 7562: my @paths_and_file = split(m|/|, $line);
7563: my $file_part = pop(@paths_and_file);
7564: chomp($file_part);
7565: my $path_part = join('/', @paths_and_file);
1.572 banghart 7566: $path_part .= '/';
7567: my $path_and_file = $path_part.$file_part;
7568: if ($path_part ne $path) {
1.800 albertel 7569: push(@return_files, ($path_and_file));
1.572 banghart 7570: }
7571: }
1.800 albertel 7572: close(OUT);
1.574 banghart 7573: return (@return_files);
1.572 banghart 7574: }
7575:
1.745 raeburn 7576: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7577:
1.745 raeburn 7578: sub get_portfile_permissions {
7579: my ($domain,$user) = @_;
1.613 albertel 7580: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7581: my ($tmp)=keys(%current_permissions);
7582: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7583: return \%current_permissions;
7584: }
7585:
7586: #---------------------------------------------Get portfolio file access controls
7587:
1.749 raeburn 7588: sub get_access_controls {
1.745 raeburn 7589: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7590: my %access;
7591: my $real_file = $file;
7592: $file =~ s/\.meta$//;
1.745 raeburn 7593: if (defined($file)) {
1.749 raeburn 7594: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7595: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7596: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7597: }
7598: }
1.745 raeburn 7599: } else {
1.749 raeburn 7600: foreach my $key (keys(%{$current_permissions})) {
7601: if ($key =~ /\0accesscontrol$/) {
7602: if (defined($group)) {
7603: if ($key !~ m-^\Q$group\E/-) {
7604: next;
7605: }
7606: }
7607: my ($fullpath) = split(/\0/,$key);
7608: if (ref($$current_permissions{$key}) eq 'HASH') {
7609: foreach my $control (keys(%{$$current_permissions{$key}})) {
7610: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7611: }
7612: }
7613: }
7614: }
7615: }
7616: return %access;
7617: }
7618:
7619: sub modify_access_controls {
7620: my ($file_name,$changes,$domain,$user)=@_;
7621: my ($outcome,$deloutcome);
7622: my %store_permissions;
7623: my %new_values;
7624: my %new_control;
7625: my %translation;
7626: my @deletions = ();
7627: my $now = time;
7628: if (exists($$changes{'activate'})) {
7629: if (ref($$changes{'activate'}) eq 'HASH') {
7630: my @newitems = sort(keys(%{$$changes{'activate'}}));
7631: my $numnew = scalar(@newitems);
7632: for (my $i=0; $i<$numnew; $i++) {
7633: my $newkey = $newitems[$i];
7634: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7635: if ($newkey =~ /^\d+:/) {
7636: $newkey =~ s/^(\d+)/$newid/;
7637: $translation{$1} = $newid;
7638: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7639: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7640: $translation{$1} = $newid;
7641: }
1.749 raeburn 7642: $new_values{$file_name."\0".$newkey} =
7643: $$changes{'activate'}{$newitems[$i]};
7644: $new_control{$newkey} = $now;
7645: }
7646: }
7647: }
7648: my %todelete;
7649: my %changed_items;
7650: foreach my $action ('delete','update') {
7651: if (exists($$changes{$action})) {
7652: if (ref($$changes{$action}) eq 'HASH') {
7653: foreach my $key (keys(%{$$changes{$action}})) {
7654: my ($itemnum) = ($key =~ /^([^:]+):/);
7655: if ($action eq 'delete') {
7656: $todelete{$itemnum} = 1;
7657: } else {
7658: $changed_items{$itemnum} = $key;
7659: }
7660: }
1.745 raeburn 7661: }
7662: }
1.749 raeburn 7663: }
7664: # get lock on access controls for file.
7665: my $lockhash = {
7666: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7667: ':'.$env{'user.domain'},
7668: };
7669: my $tries = 0;
7670: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7671:
7672: while (($gotlock ne 'ok') && $tries <3) {
7673: $tries ++;
7674: sleep 1;
7675: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7676: }
7677: if ($gotlock eq 'ok') {
7678: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7679: my ($tmp)=keys(%curr_permissions);
7680: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7681: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7682: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7683: if (ref($curr_controls) eq 'HASH') {
7684: foreach my $control_item (keys(%{$curr_controls})) {
7685: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7686: if (defined($todelete{$itemnum})) {
7687: push(@deletions,$file_name."\0".$control_item);
7688: } else {
7689: if (defined($changed_items{$itemnum})) {
7690: $new_control{$changed_items{$itemnum}} = $now;
7691: push(@deletions,$file_name."\0".$control_item);
7692: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7693: } else {
7694: $new_control{$control_item} = $$curr_controls{$control_item};
7695: }
7696: }
1.745 raeburn 7697: }
7698: }
7699: }
1.970 raeburn 7700: my ($group);
7701: if (&is_course($domain,$user)) {
7702: ($group,my $file) = split(/\//,$file_name,2);
7703: }
1.749 raeburn 7704: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7705: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7706: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7707: # remove lock
7708: my @del_lock = ($file_name."\0".'locked_access_records');
7709: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7710: my $sqlresult =
1.970 raeburn 7711: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7712: $group);
1.749 raeburn 7713: } else {
7714: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7715: }
1.749 raeburn 7716: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7717: }
7718:
1.827 raeburn 7719: sub make_public_indefinitely {
7720: my ($requrl) = @_;
7721: my $now = time;
7722: my $action = 'activate';
7723: my $aclnum = 0;
7724: if (&is_portfolio_url($requrl)) {
7725: my (undef,$udom,$unum,$file_name,$group) =
7726: &parse_portfolio_url($requrl);
7727: my $current_perms = &get_portfile_permissions($udom,$unum);
7728: my %access_controls = &get_access_controls($current_perms,
7729: $group,$file_name);
7730: foreach my $key (keys(%{$access_controls{$file_name}})) {
7731: my ($num,$scope,$end,$start) =
7732: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7733: if ($scope eq 'public') {
7734: if ($start <= $now && $end == 0) {
7735: $action = 'none';
7736: } else {
7737: $action = 'update';
7738: $aclnum = $num;
7739: }
7740: last;
7741: }
7742: }
7743: if ($action eq 'none') {
7744: return 'ok';
7745: } else {
7746: my %changes;
7747: my $newend = 0;
7748: my $newstart = $now;
7749: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7750: $changes{$action}{$newkey} = {
7751: type => 'public',
7752: time => {
7753: start => $newstart,
7754: end => $newend,
7755: },
7756: };
7757: my ($outcome,$deloutcome,$new_values,$translation) =
7758: &modify_access_controls($file_name,\%changes,$udom,$unum);
7759: return $outcome;
7760: }
7761: } else {
7762: return 'invalid';
7763: }
7764: }
7765:
1.745 raeburn 7766: #------------------------------------------------------Get Marked as Read Only
7767:
7768: sub get_marked_as_readonly {
7769: my ($domain,$user,$what,$group) = @_;
7770: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7771: my @readonly_files;
1.629 banghart 7772: my $cmp1=$what;
7773: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7774: while (my ($file_name,$value) = each(%{$current_permissions})) {
7775: if (defined($group)) {
7776: if ($file_name !~ m-^\Q$group\E/-) {
7777: next;
7778: }
7779: }
1.561 banghart 7780: if (ref($value) eq "ARRAY"){
7781: foreach my $stored_what (@{$value}) {
1.629 banghart 7782: my $cmp2=$stored_what;
1.759 albertel 7783: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7784: $cmp2=join('',@{$stored_what});
1.745 raeburn 7785: }
1.629 banghart 7786: if ($cmp1 eq $cmp2) {
1.561 banghart 7787: push(@readonly_files, $file_name);
1.745 raeburn 7788: last;
1.563 banghart 7789: } elsif (!defined($what)) {
7790: push(@readonly_files, $file_name);
1.745 raeburn 7791: last;
1.561 banghart 7792: }
7793: }
1.745 raeburn 7794: }
1.561 banghart 7795: }
7796: return @readonly_files;
7797: }
1.577 banghart 7798: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7799:
1.577 banghart 7800: sub get_marked_as_readonly_hash {
1.745 raeburn 7801: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7802: my %readonly_files;
1.745 raeburn 7803: while (my ($file_name,$value) = each(%{$current_permissions})) {
7804: if (defined($group)) {
7805: if ($file_name !~ m-^\Q$group\E/-) {
7806: next;
7807: }
7808: }
1.577 banghart 7809: if (ref($value) eq "ARRAY"){
7810: foreach my $stored_what (@{$value}) {
1.745 raeburn 7811: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7812: foreach my $lock_descriptor(@{$stored_what}) {
7813: if ($lock_descriptor eq 'graded') {
7814: $readonly_files{$file_name} = 'graded';
7815: } elsif ($lock_descriptor eq 'handback') {
7816: $readonly_files{$file_name} = 'handback';
7817: } else {
7818: if (!exists($readonly_files{$file_name})) {
7819: $readonly_files{$file_name} = 'locked';
7820: }
7821: }
1.745 raeburn 7822: }
1.750 banghart 7823: }
1.577 banghart 7824: }
7825: }
7826: }
7827: return %readonly_files;
7828: }
1.559 banghart 7829: # ------------------------------------------------------------ Unmark as Read Only
7830:
7831: sub unmark_as_readonly {
1.629 banghart 7832: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7833: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7834: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7835: $file_name = &declutter_portfile($file_name);
1.634 albertel 7836: my $symb_crs = $what;
7837: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7838: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7839: my ($tmp)=keys(%current_permissions);
7840: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7841: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7842: foreach my $file (@readonly_files) {
1.759 albertel 7843: my $clean_file = &declutter_portfile($file);
7844: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7845: my $current_locks = $current_permissions{$file};
1.563 banghart 7846: my @new_locks;
7847: my @del_keys;
7848: if (ref($current_locks) eq "ARRAY"){
7849: foreach my $locker (@{$current_locks}) {
1.632 albertel 7850: my $compare=$locker;
1.749 raeburn 7851: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7852: $compare=join('',@{$locker});
1.746 raeburn 7853: if ($compare ne $symb_crs) {
7854: push(@new_locks, $locker);
7855: }
1.563 banghart 7856: }
7857: }
1.650 albertel 7858: if (scalar(@new_locks) > 0) {
1.563 banghart 7859: $current_permissions{$file} = \@new_locks;
7860: } else {
7861: push(@del_keys, $file);
1.613 albertel 7862: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7863: delete($current_permissions{$file});
1.563 banghart 7864: }
7865: }
1.561 banghart 7866: }
1.613 albertel 7867: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7868: return;
7869: }
1.512 banghart 7870:
1.17 www 7871: # ------------------------------------------------------------ Directory lister
7872:
7873: sub dirlist {
1.955 raeburn 7874: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7875: $uri=~s/^\///;
7876: $uri=~s/\/$//;
1.253 stredwic 7877: my ($udom, $uname);
1.955 raeburn 7878: if ($getuserdir) {
1.253 stredwic 7879: $udom = $userdomain;
7880: $uname = $username;
1.955 raeburn 7881: } else {
7882: (undef,$udom,$uname)=split(/\//,$uri);
7883: if(defined($userdomain)) {
7884: $udom = $userdomain;
7885: }
7886: if(defined($username)) {
7887: $uname = $username;
7888: }
1.253 stredwic 7889: }
1.955 raeburn 7890: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7891:
1.955 raeburn 7892: $dirRoot = $perlvar{'lonDocRoot'};
7893: if (defined($getpropath)) {
7894: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7895: $dirRoot =~ s/\/$//;
1.955 raeburn 7896: } elsif (defined($getuserdir)) {
7897: my $subdir=$uname.'__';
7898: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7899: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7900: ."/$udom/$subdir/$uname";
7901: } elsif (defined($alternateRoot)) {
7902: $dirRoot = $alternateRoot;
1.751 banghart 7903: }
1.253 stredwic 7904:
7905: if($udom) {
7906: if($uname) {
1.955 raeburn 7907: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7908: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7909: .':'.&escape($uname).':'.&escape($udom),
7910: &homeserver($uname,$udom));
7911: if ($listing eq 'unknown_cmd') {
7912: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7913: &homeserver($uname,$udom));
7914: } else {
7915: @listing_results = map { &unescape($_); } split(/:/,$listing);
7916: }
1.605 matthew 7917: if ($listing eq 'unknown_cmd') {
1.800 albertel 7918: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7919: &homeserver($uname,$udom));
1.605 matthew 7920: @listing_results = split(/:/,$listing);
7921: } else {
7922: @listing_results = map { &unescape($_); } split(/:/,$listing);
7923: }
7924: return @listing_results;
1.955 raeburn 7925: } elsif(!$alternateRoot) {
1.800 albertel 7926: my %allusers;
1.841 albertel 7927: my %servers = &get_servers($udom,'library');
1.955 raeburn 7928: foreach my $tryserver (keys(%servers)) {
7929: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7930: &escape($udom),$tryserver);
7931: if ($listing eq 'unknown_cmd') {
7932: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7933: $udom, $tryserver);
7934: } else {
7935: @listing_results = map { &unescape($_); } split(/:/,$listing);
7936: }
1.841 albertel 7937: if ($listing eq 'unknown_cmd') {
7938: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7939: $udom, $tryserver);
7940: @listing_results = split(/:/,$listing);
7941: } else {
7942: @listing_results =
7943: map { &unescape($_); } split(/:/,$listing);
7944: }
7945: if ($listing_results[0] ne 'no_such_dir' &&
7946: $listing_results[0] ne 'empty' &&
7947: $listing_results[0] ne 'con_lost') {
7948: foreach my $line (@listing_results) {
7949: my ($entry) = split(/&/,$line,2);
7950: $allusers{$entry} = 1;
7951: }
7952: }
1.253 stredwic 7953: }
7954: my $alluserstr='';
1.800 albertel 7955: foreach my $user (sort(keys(%allusers))) {
7956: $alluserstr.=$user.'&user:';
1.253 stredwic 7957: }
7958: $alluserstr=~s/:$//;
7959: return split(/:/,$alluserstr);
7960: } else {
1.800 albertel 7961: return ('missing user name');
1.253 stredwic 7962: }
1.955 raeburn 7963: } elsif(!defined($getpropath)) {
1.841 albertel 7964: my @all_domains = sort(&all_domains());
1.955 raeburn 7965: foreach my $domain (@all_domains) {
7966: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7967: }
7968: return @all_domains;
7969: } else {
1.800 albertel 7970: return ('missing domain');
1.275 stredwic 7971: }
7972: }
7973:
7974: # --------------------------------------------- GetFileTimestamp
7975: # This function utilizes dirlist and returns the date stamp for
7976: # when it was last modified. It will also return an error of -1
7977: # if an error occurs
7978:
7979: sub GetFileTimestamp {
1.955 raeburn 7980: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7981: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7982: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7983: my ($fileStat) =
7984: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7985: undef,$getuserdir);
1.275 stredwic 7986: my @stats = split('&', $fileStat);
7987: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7988: # @stats contains first the filename, then the stat output
7989: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7990: } else {
7991: return -1;
1.253 stredwic 7992: }
1.26 www 7993: }
7994:
1.712 albertel 7995: sub stat_file {
7996: my ($uri) = @_;
1.787 albertel 7997: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7998:
1.955 raeburn 7999: my ($udom,$uname,$file);
1.712 albertel 8000: if ($uri =~ m-^/(uploaded|editupload)/-) {
8001: ($udom,$uname,$file) =
1.811 albertel 8002: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8003: $file = 'userfiles/'.$file;
8004: }
8005: if ($uri =~ m-^/res/-) {
8006: ($udom,$uname) =
1.807 albertel 8007: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8008: $file = $uri;
8009: }
8010:
8011: if (!$udom || !$uname || !$file) {
8012: # unable to handle the uri
8013: return ();
8014: }
1.956 raeburn 8015: my $getpropath;
8016: if ($file =~ /^userfiles\//) {
8017: $getpropath = 1;
8018: }
1.955 raeburn 8019: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 8020: my @stats = split('&', $result);
1.721 banghart 8021:
1.712 albertel 8022: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8023: shift(@stats); #filename is first
8024: return @stats;
8025: }
8026: return ();
8027: }
8028:
1.26 www 8029: # -------------------------------------------------------- Value of a Condition
8030:
1.713 albertel 8031: # gets the value of a specific preevaluated condition
8032: # stored in the string $env{user.state.<cid>}
8033: # or looks up a condition reference in the bighash and if if hasn't
8034: # already been evaluated recurses into docondval to get the value of
8035: # the condition, then memoizing it to
8036: # $env{user.state.<cid>.<condition>}
1.40 www 8037: sub directcondval {
8038: my $number=shift;
1.620 albertel 8039: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8040: &Apache::lonuserstate::evalstate();
8041: }
1.713 albertel 8042: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8043: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8044: } elsif ($number =~ /^_/) {
8045: my $sub_condition;
8046: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8047: &GDBM_READER(),0640)) {
8048: $sub_condition=$bighash{'conditions'.$number};
8049: untie(%bighash);
8050: }
8051: my $value = &docondval($sub_condition);
1.949 raeburn 8052: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8053: return $value;
8054: }
1.620 albertel 8055: if ($env{'user.state.'.$env{'request.course.id'}}) {
8056: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8057: } else {
8058: return 2;
8059: }
8060: }
8061:
1.713 albertel 8062: # get the collection of conditions for this resource
1.26 www 8063: sub condval {
8064: my $condidx=shift;
1.54 www 8065: my $allpathcond='';
1.713 albertel 8066: foreach my $cond (split(/\|/,$condidx)) {
8067: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8068: $allpathcond.=
8069: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8070: }
1.191 harris41 8071: }
1.54 www 8072: $allpathcond=~s/\|$//;
1.713 albertel 8073: return &docondval($allpathcond);
8074: }
8075:
8076: #evaluates an expression of conditions
8077: sub docondval {
8078: my ($allpathcond) = @_;
8079: my $result=0;
8080: if ($env{'request.course.id'}
8081: && defined($allpathcond)) {
8082: my $operand='|';
8083: my @stack;
8084: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8085: if ($chunk eq '(') {
8086: push @stack,($operand,$result);
8087: } elsif ($chunk eq ')') {
8088: my $before=pop @stack;
8089: if (pop @stack eq '&') {
8090: $result=$result>$before?$before:$result;
8091: } else {
8092: $result=$result>$before?$result:$before;
8093: }
8094: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8095: $operand=$chunk;
8096: } else {
8097: my $new=directcondval($chunk);
8098: if ($operand eq '&') {
8099: $result=$result>$new?$new:$result;
8100: } else {
8101: $result=$result>$new?$result:$new;
8102: }
8103: }
8104: }
1.26 www 8105: }
8106: return $result;
1.421 albertel 8107: }
8108:
8109: # ---------------------------------------------------- Devalidate courseresdata
8110:
8111: sub devalidatecourseresdata {
8112: my ($coursenum,$coursedomain)=@_;
8113: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8114: &devalidate_cache_new('courseres',$hashid);
1.28 www 8115: }
8116:
1.763 www 8117:
1.200 www 8118: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8119: #
8120: # Parameters:
8121: # $coursenum - Number of the course.
8122: # $coursedomain - Domain at which the course was created.
8123: # Returns:
8124: # A hash of the course parameters along (I think) with timestamps
8125: # and version info.
1.877 foxr 8126:
1.624 albertel 8127: sub get_courseresdata {
8128: my ($coursenum,$coursedomain)=@_;
1.200 www 8129: my $coursehom=&homeserver($coursenum,$coursedomain);
8130: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8131: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8132: my %dumpreply;
1.417 albertel 8133: unless (defined($cached)) {
1.624 albertel 8134: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8135: $result=\%dumpreply;
1.251 albertel 8136: my ($tmp) = keys(%dumpreply);
8137: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8138: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8139: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8140: return $tmp;
1.416 albertel 8141: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8142: $result=undef;
1.599 albertel 8143: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8144: }
8145: }
1.624 albertel 8146: return $result;
8147: }
8148:
1.633 albertel 8149: sub devalidateuserresdata {
8150: my ($uname,$udom)=@_;
8151: my $hashid="$udom:$uname";
8152: &devalidate_cache_new('userres',$hashid);
8153: }
8154:
1.624 albertel 8155: sub get_userresdata {
8156: my ($uname,$udom)=@_;
8157: #most student don\'t have any data set, check if there is some data
8158: if (&EXT_cache_status($udom,$uname)) { return undef; }
8159:
8160: my $hashid="$udom:$uname";
8161: my ($result,$cached)=&is_cached_new('userres',$hashid);
8162: if (!defined($cached)) {
8163: my %resourcedata=&dump('resourcedata',$udom,$uname);
8164: $result=\%resourcedata;
8165: &do_cache_new('userres',$hashid,$result,600);
8166: }
8167: my ($tmp)=keys(%$result);
8168: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8169: return $result;
8170: }
8171: #error 2 occurs when the .db doesn't exist
8172: if ($tmp!~/error: 2 /) {
1.672 albertel 8173: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8174: " Trying to get resource data for ".
8175: $uname." at ".$udom.": ".
8176: $tmp."</font>");
8177: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8178: #&EXT_cache_set($udom,$uname);
8179: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8180: undef($tmp); # not really an error so don't send it back
1.624 albertel 8181: }
8182: return $tmp;
8183: }
1.879 foxr 8184: #----------------------------------------------- resdata - return resource data
8185: # Purpose:
8186: # Return resource data for either users or for a course.
8187: # Parameters:
8188: # $name - Course/user name.
8189: # $domain - Name of the domain the user/course is registered on.
8190: # $type - Type of thing $name is (must be 'course' or 'user'
8191: # @which - Array of names of resources desired.
8192: # Returns:
8193: # The value of the first reasource in @which that is found in the
8194: # resource hash.
8195: # Exceptional Conditions:
8196: # If the $type passed in is not valid (not the string 'course' or
8197: # 'user', an undefined reference is returned.
8198: # If none of the resources are found, an undef is returned
1.624 albertel 8199: sub resdata {
8200: my ($name,$domain,$type,@which)=@_;
8201: my $result;
8202: if ($type eq 'course') {
8203: $result=&get_courseresdata($name,$domain);
8204: } elsif ($type eq 'user') {
8205: $result=&get_userresdata($name,$domain);
8206: }
8207: if (!ref($result)) { return $result; }
1.251 albertel 8208: foreach my $item (@which) {
1.927 albertel 8209: if (defined($result->{$item->[0]})) {
8210: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8211: }
1.250 albertel 8212: }
1.291 albertel 8213: return undef;
1.200 www 8214: }
8215:
1.379 matthew 8216: #
8217: # EXT resource caching routines
8218: #
8219:
8220: sub clear_EXT_cache_status {
1.383 albertel 8221: &delenv('cache.EXT.');
1.379 matthew 8222: }
8223:
8224: sub EXT_cache_status {
8225: my ($target_domain,$target_user) = @_;
1.383 albertel 8226: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8227: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8228: # We know already the user has no data
8229: return 1;
8230: } else {
8231: return 0;
8232: }
8233: }
8234:
8235: sub EXT_cache_set {
8236: my ($target_domain,$target_user) = @_;
1.383 albertel 8237: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8238: #&appenv({$cachename => time});
1.379 matthew 8239: }
8240:
1.28 www 8241: # --------------------------------------------------------- Value of a Variable
1.58 www 8242: sub EXT {
1.715 albertel 8243:
1.395 albertel 8244: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8245: unless ($varname) { return ''; }
1.218 albertel 8246: #get real user name/domain, courseid and symb
8247: my $courseid;
1.359 albertel 8248: my $publicuser;
1.427 www 8249: if ($symbparm) {
8250: $symbparm=&get_symb_from_alias($symbparm);
8251: }
1.218 albertel 8252: if (!($uname && $udom)) {
1.790 albertel 8253: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8254: if (!$symbparm) { $symbparm=$cursymb; }
8255: } else {
1.620 albertel 8256: $courseid=$env{'request.course.id'};
1.218 albertel 8257: }
1.48 www 8258: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8259: my $rest;
1.320 albertel 8260: if (defined($therest[0])) {
1.48 www 8261: $rest=join('.',@therest);
8262: } else {
8263: $rest='';
8264: }
1.320 albertel 8265:
1.57 www 8266: my $qualifierrest=$qualifier;
8267: if ($rest) { $qualifierrest.='.'.$rest; }
8268: my $spacequalifierrest=$space;
8269: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8270: if ($realm eq 'user') {
1.48 www 8271: # --------------------------------------------------------------- user.resource
8272: if ($space eq 'resource') {
1.651 albertel 8273: if ( (defined($Apache::lonhomework::parsing_a_problem)
8274: || defined($Apache::lonhomework::parsing_a_task))
8275: &&
1.744 albertel 8276: ($symbparm eq &symbread()) ) {
8277: # if we are in the middle of processing the resource the
8278: # get the value we are planning on committing
8279: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8280: return $Apache::lonhomework::results{$qualifierrest};
8281: } else {
8282: return $Apache::lonhomework::history{$qualifierrest};
8283: }
1.335 albertel 8284: } else {
1.359 albertel 8285: my %restored;
1.620 albertel 8286: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8287: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8288: } else {
8289: %restored=&restore($symbparm,$courseid,$udom,$uname);
8290: }
1.335 albertel 8291: return $restored{$qualifierrest};
8292: }
1.48 www 8293: # ----------------------------------------------------------------- user.access
8294: } elsif ($space eq 'access') {
1.218 albertel 8295: # FIXME - not supporting calls for a specific user
1.48 www 8296: return &allowed($qualifier,$rest);
8297: # ------------------------------------------ user.preferences, user.environment
8298: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8299: if (($uname eq $env{'user.name'}) &&
8300: ($udom eq $env{'user.domain'})) {
8301: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8302: } else {
1.359 albertel 8303: my %returnhash;
8304: if (!$publicuser) {
8305: %returnhash=&userenvironment($udom,$uname,
8306: $qualifierrest);
8307: }
1.218 albertel 8308: return $returnhash{$qualifierrest};
8309: }
1.48 www 8310: # ----------------------------------------------------------------- user.course
8311: } elsif ($space eq 'course') {
1.218 albertel 8312: # FIXME - not supporting calls for a specific user
1.620 albertel 8313: return $env{join('.',('request.course',$qualifier))};
1.48 www 8314: # ------------------------------------------------------------------- user.role
8315: } elsif ($space eq 'role') {
1.218 albertel 8316: # FIXME - not supporting calls for a specific user
1.620 albertel 8317: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8318: if ($qualifier eq 'value') {
8319: return $role;
8320: } elsif ($qualifier eq 'extent') {
8321: return $where;
8322: }
8323: # ----------------------------------------------------------------- user.domain
8324: } elsif ($space eq 'domain') {
1.218 albertel 8325: return $udom;
1.48 www 8326: # ------------------------------------------------------------------- user.name
8327: } elsif ($space eq 'name') {
1.218 albertel 8328: return $uname;
1.48 www 8329: # ---------------------------------------------------- Any other user namespace
1.29 www 8330: } else {
1.359 albertel 8331: my %reply;
8332: if (!$publicuser) {
8333: %reply=&get($space,[$qualifierrest],$udom,$uname);
8334: }
8335: return $reply{$qualifierrest};
1.48 www 8336: }
1.236 www 8337: } elsif ($realm eq 'query') {
8338: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8339: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8340: [$spacequalifierrest]);
1.620 albertel 8341: return $env{'form.'.$spacequalifierrest};
1.236 www 8342: } elsif ($realm eq 'request') {
1.48 www 8343: # ------------------------------------------------------------- request.browser
8344: if ($space eq 'browser') {
1.430 www 8345: if ($qualifier eq 'textremote') {
1.676 albertel 8346: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8347: return 1;
8348: } else {
8349: return 0;
8350: }
8351: } else {
1.620 albertel 8352: return $env{'browser.'.$qualifier};
1.430 www 8353: }
1.57 www 8354: # ------------------------------------------------------------ request.filename
8355: } else {
1.620 albertel 8356: return $env{'request.'.$spacequalifierrest};
1.29 www 8357: }
1.28 www 8358: } elsif ($realm eq 'course') {
1.48 www 8359: # ---------------------------------------------------------- course.description
1.620 albertel 8360: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8361: } elsif ($realm eq 'resource') {
1.165 www 8362:
1.620 albertel 8363: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8364: if (!$symbparm) { $symbparm=&symbread(); }
8365: }
1.693 albertel 8366:
8367: if ($space eq 'title') {
8368: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8369: return &gettitle($symbparm);
8370: }
8371:
8372: if ($space eq 'map') {
8373: my ($map) = &decode_symb($symbparm);
8374: return &symbread($map);
8375: }
1.905 albertel 8376: if ($space eq 'filename') {
8377: if ($symbparm) {
8378: return &clutter((&decode_symb($symbparm))[2]);
8379: }
8380: return &hreflocation('',$env{'request.filename'});
8381: }
1.693 albertel 8382:
8383: my ($section, $group, @groups);
1.593 albertel 8384: my ($courselevelm,$courselevel);
1.539 albertel 8385: if ($symbparm && defined($courseid) &&
1.620 albertel 8386: $courseid eq $env{'request.course.id'}) {
1.165 www 8387:
1.218 albertel 8388: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8389:
1.60 www 8390: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8391: my $symbp=$symbparm;
1.735 albertel 8392: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8393:
8394: my $symbparm=$symbp.'.'.$spacequalifierrest;
8395: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8396:
1.620 albertel 8397: if (($env{'user.name'} eq $uname) &&
8398: ($env{'user.domain'} eq $udom)) {
8399: $section=$env{'request.course.sec'};
1.733 raeburn 8400: @groups = split(/:/,$env{'request.course.groups'});
8401: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8402: } else {
1.539 albertel 8403: if (! defined($usection)) {
1.551 albertel 8404: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8405: } else {
8406: $section = $usection;
8407: }
1.733 raeburn 8408: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8409: }
8410:
8411: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8412: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8413: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8414:
1.593 albertel 8415: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8416: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8417: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8418:
1.60 www 8419: # ----------------------------------------------------------- first, check user
1.624 albertel 8420:
8421: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8422: ([$courselevelr,'resource'],
8423: [$courselevelm,'map' ],
8424: [$courselevel, 'course' ]));
1.931 albertel 8425: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8426:
1.594 albertel 8427: # ------------------------------------------------ second, check some of course
1.684 raeburn 8428: my $coursereply;
1.691 raeburn 8429: if (@groups > 0) {
8430: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8431: $mapparm,$spacequalifierrest);
1.927 albertel 8432: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8433: }
1.96 www 8434:
1.684 raeburn 8435: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8436: $env{'course.'.$courseid.'.domain'},
8437: 'course',
8438: ([$seclevelr, 'resource'],
8439: [$seclevelm, 'map' ],
8440: [$seclevel, 'course' ],
8441: [$courselevelr,'resource']));
8442: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8443:
1.60 www 8444: # ------------------------------------------------------ third, check map parms
1.218 albertel 8445: my %parmhash=();
8446: my $thisparm='';
8447: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8448: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8449: &GDBM_READER(),0640)) {
1.218 albertel 8450: $thisparm=$parmhash{$symbparm};
8451: untie(%parmhash);
8452: }
1.927 albertel 8453: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8454: }
1.594 albertel 8455: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8456:
1.218 albertel 8457: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8458: my $filename;
8459: if (!$symbparm) { $symbparm=&symbread(); }
8460: if ($symbparm) {
1.409 www 8461: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8462: } else {
1.620 albertel 8463: $filename=$env{'request.filename'};
1.282 albertel 8464: }
8465: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8466: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8467: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8468: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8469:
1.927 albertel 8470: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8471: if ($symbparm && defined($courseid) &&
1.620 albertel 8472: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8473: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8474: $env{'course.'.$courseid.'.domain'},
8475: 'course',
1.927 albertel 8476: ([$courselevelm,'map' ],
8477: [$courselevel, 'course']));
8478: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8479: }
1.145 www 8480: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8481: unless ($space eq '0') {
1.336 albertel 8482: my @parts=split(/_/,$space);
8483: my $id=pop(@parts);
8484: my $part=join('_',@parts);
8485: if ($part eq '') { $part='0'; }
1.927 albertel 8486: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8487: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8488: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8489: }
1.395 albertel 8490: if ($recurse) { return undef; }
8491: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8492: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8493: # ---------------------------------------------------- Any other user namespace
8494: } elsif ($realm eq 'environment') {
8495: # ----------------------------------------------------------------- environment
1.620 albertel 8496: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8497: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8498: } else {
1.770 albertel 8499: if ($uname eq 'anonymous' && $udom eq '') {
8500: return '';
8501: }
1.219 albertel 8502: my %returnhash=&userenvironment($udom,$uname,
8503: $spacequalifierrest);
8504: return $returnhash{$spacequalifierrest};
8505: }
1.28 www 8506: } elsif ($realm eq 'system') {
1.48 www 8507: # ----------------------------------------------------------------- system.time
8508: if ($space eq 'time') {
8509: return time;
8510: }
1.696 albertel 8511: } elsif ($realm eq 'server') {
8512: # ----------------------------------------------------------------- system.time
8513: if ($space eq 'name') {
8514: return $ENV{'SERVER_NAME'};
8515: }
1.28 www 8516: }
1.48 www 8517: return '';
1.61 www 8518: }
8519:
1.927 albertel 8520: sub get_reply {
8521: my ($reply_value) = @_;
1.940 raeburn 8522: if (ref($reply_value) eq 'ARRAY') {
8523: if (wantarray) {
8524: return @$reply_value;
8525: }
8526: return $reply_value->[0];
8527: } else {
8528: return $reply_value;
1.927 albertel 8529: }
8530: }
8531:
1.691 raeburn 8532: sub check_group_parms {
8533: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8534: my @groupitems = ();
8535: my $resultitem;
1.927 albertel 8536: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8537: foreach my $group (@{$groups}) {
8538: foreach my $level (@levels) {
1.927 albertel 8539: my $item = $courseid.'.['.$group.'].'.$level->[0];
8540: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8541: }
8542: }
8543: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8544: $env{'course.'.$courseid.'.domain'},
8545: 'course',@groupitems);
8546: return $coursereply;
8547: }
8548:
8549: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8550: my ($courseid,@groups) = @_;
8551: @groups = sort(@groups);
1.691 raeburn 8552: return @groups;
8553: }
8554:
1.395 albertel 8555: sub packages_tab_default {
8556: my ($uri,$varname)=@_;
8557: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8558:
8559: my (@extension,@specifics,$do_default);
8560: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8561: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8562: if ($pack_type eq 'default') {
8563: $do_default=1;
8564: } elsif ($pack_type eq 'extension') {
8565: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8566: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8567: # only look at packages defaults for packages that this id is
1.738 albertel 8568: push(@specifics,[$package,$pack_type,$pack_part]);
8569: }
8570: }
8571: # first look for a package that matches the requested part id
8572: foreach my $package (@specifics) {
8573: my (undef,$pack_type,$pack_part)=@{$package};
8574: next if ($pack_part ne $part);
8575: if (defined($packagetab{"$pack_type&$name&default"})) {
8576: return $packagetab{"$pack_type&$name&default"};
8577: }
8578: }
8579: # look for any possible matching non extension_ package
8580: foreach my $package (@specifics) {
8581: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8582: if (defined($packagetab{"$pack_type&$name&default"})) {
8583: return $packagetab{"$pack_type&$name&default"};
8584: }
1.585 albertel 8585: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8586: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8587: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8588: }
8589: }
1.738 albertel 8590: # look for any posible extension_ match
8591: foreach my $package (@extension) {
8592: my ($package,$pack_type)=@{$package};
8593: if (defined($packagetab{"$pack_type&$name&default"})) {
8594: return $packagetab{"$pack_type&$name&default"};
8595: }
8596: if (defined($packagetab{$package."&$name&default"})) {
8597: return $packagetab{$package."&$name&default"};
8598: }
8599: }
8600: # look for a global default setting
8601: if ($do_default && defined($packagetab{"default&$name&default"})) {
8602: return $packagetab{"default&$name&default"};
8603: }
1.395 albertel 8604: return undef;
8605: }
8606:
1.334 albertel 8607: sub add_prefix_and_part {
8608: my ($prefix,$part)=@_;
8609: my $keyroot;
8610: if (defined($prefix) && $prefix !~ /^__/) {
8611: # prefix that has a part already
8612: $keyroot=$prefix;
8613: } elsif (defined($prefix)) {
8614: # prefix that is missing a part
8615: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8616: } else {
8617: # no prefix at all
8618: if (defined($part)) { $keyroot='_'.$part; }
8619: }
8620: return $keyroot;
8621: }
8622:
1.71 www 8623: # ---------------------------------------------------------------- Get metadata
8624:
1.599 albertel 8625: my %metaentry;
1.71 www 8626: sub metadata {
1.176 www 8627: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8628: $uri=&declutter($uri);
1.288 albertel 8629: # if it is a non metadata possible uri return quickly
1.529 albertel 8630: if (($uri eq '') ||
8631: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8632: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26 raeburn 8633: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8634: return undef;
8635: }
8636: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8637: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8638: return undef;
1.288 albertel 8639: }
1.73 www 8640: my $filename=$uri;
8641: $uri=~s/\.meta$//;
1.172 www 8642: #
8643: # Is the metadata already cached?
1.177 www 8644: # Look at timestamp of caching
1.172 www 8645: # Everything is cached by the main uri, libraries are never directly cached
8646: #
1.428 albertel 8647: if (!defined($liburi)) {
1.599 albertel 8648: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8649: if (defined($cached)) { return $result->{':'.$what}; }
8650: }
8651: {
1.172 www 8652: #
8653: # Is this a recursive call for a library?
8654: #
1.599 albertel 8655: # if (! exists($metacache{$uri})) {
8656: # $metacache{$uri}={};
8657: # }
1.924 albertel 8658: my $cachetime = 60*60;
1.171 www 8659: if ($liburi) {
8660: $liburi=&declutter($liburi);
8661: $filename=$liburi;
1.401 bowersj2 8662: } else {
1.599 albertel 8663: &devalidate_cache_new('meta',$uri);
8664: undef(%metaentry);
1.401 bowersj2 8665: }
1.140 www 8666: my %metathesekeys=();
1.73 www 8667: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8668: my $metastring;
1.924 albertel 8669: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8670: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8671: $metastring =
1.929 albertel 8672: &Apache::lonnet::ssi_body($which,
1.924 albertel 8673: ('grade_target' => 'meta'));
8674: $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26 raeburn 8675: } elsif (($uri !~ m -^(editupload)/-) &&
8676: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 8677: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8678: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8679: $metastring=&getfile($file);
1.489 albertel 8680: }
1.208 albertel 8681: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8682: my $token;
1.140 www 8683: undef %metathesekeys;
1.71 www 8684: while ($token=$parser->get_token) {
1.339 albertel 8685: if ($token->[0] eq 'S') {
8686: if (defined($token->[2]->{'package'})) {
1.172 www 8687: #
8688: # This is a package - get package info
8689: #
1.339 albertel 8690: my $package=$token->[2]->{'package'};
8691: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8692: if (defined($token->[2]->{'id'})) {
8693: $keyroot.='_'.$token->[2]->{'id'};
8694: }
1.599 albertel 8695: if ($metaentry{':packages'}) {
8696: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8697: } else {
1.599 albertel 8698: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8699: }
1.736 albertel 8700: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8701: my $part=$keyroot;
8702: $part=~s/^\_//;
1.736 albertel 8703: if ($pack_entry=~/^\Q$package\E\&/ ||
8704: $pack_entry=~/^\Q$package\E_0\&/) {
8705: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8706: # ignore package.tab specified default values
8707: # here &package_tab_default() will fetch those
8708: if ($subp eq 'default') { next; }
1.736 albertel 8709: my $value=$packagetab{$pack_entry};
1.432 albertel 8710: my $unikey;
8711: if ($pack =~ /_0$/) {
8712: $unikey='parameter_0_'.$name;
8713: $part=0;
8714: } else {
8715: $unikey='parameter'.$keyroot.'_'.$name;
8716: }
1.339 albertel 8717: if ($subp eq 'display') {
8718: $value.=' [Part: '.$part.']';
8719: }
1.599 albertel 8720: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8721: $metathesekeys{$unikey}=1;
1.599 albertel 8722: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8723: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8724: }
1.599 albertel 8725: if (defined($metaentry{':'.$unikey.'.default'})) {
8726: $metaentry{':'.$unikey}=
8727: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8728: }
1.339 albertel 8729: }
8730: }
8731: } else {
1.172 www 8732: #
8733: # This is not a package - some other kind of start tag
1.339 albertel 8734: #
8735: my $entry=$token->[1];
8736: my $unikey;
8737: if ($entry eq 'import') {
8738: $unikey='';
8739: } else {
8740: $unikey=$entry;
8741: }
8742: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8743:
8744: if (defined($token->[2]->{'id'})) {
8745: $unikey.='_'.$token->[2]->{'id'};
8746: }
1.175 www 8747:
1.339 albertel 8748: if ($entry eq 'import') {
1.175 www 8749: #
8750: # Importing a library here
1.339 albertel 8751: #
8752: if ($depthcount<20) {
8753: my $location=$parser->get_text('/import');
8754: my $dir=$filename;
8755: $dir=~s|[^/]*$||;
8756: $location=&filelocation($dir,$location);
1.736 albertel 8757: my $metadata =
8758: &metadata($uri,'keys', $location,$unikey,
8759: $depthcount+1);
8760: foreach my $meta (split(',',$metadata)) {
8761: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8762: $metathesekeys{$meta}=1;
1.339 albertel 8763: }
8764: }
8765: } else {
8766: if (defined($token->[2]->{'name'})) {
8767: $unikey.='_'.$token->[2]->{'name'};
8768: }
8769: $metathesekeys{$unikey}=1;
1.736 albertel 8770: foreach my $param (@{$token->[3]}) {
8771: $metaentry{':'.$unikey.'.'.$param} =
8772: $token->[2]->{$param};
1.339 albertel 8773: }
8774: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8775: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8776: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8777: # only ws inside the tag, and not in default, so use default
8778: # as value
1.599 albertel 8779: $metaentry{':'.$unikey}=$default;
1.908 albertel 8780: } elsif ( $internaltext =~ /\S/ ) {
8781: # something interesting inside the tag
8782: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8783: } else {
1.908 albertel 8784: # no interesting values, don't set a default
1.339 albertel 8785: }
1.172 www 8786: # end of not-a-package not-a-library import
1.339 albertel 8787: }
1.172 www 8788: # end of not-a-package start tag
1.339 albertel 8789: }
1.172 www 8790: # the next is the end of "start tag"
1.339 albertel 8791: }
8792: }
1.483 albertel 8793: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8794: $extension = lc($extension);
8795: if ($extension eq 'htm') { $extension='html'; }
8796:
1.737 albertel 8797: foreach my $key (keys(%packagetab)) {
1.483 albertel 8798: #no specific packages #how's our extension
8799: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8800: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8801: \%metathesekeys);
8802: }
1.883 albertel 8803:
8804: if (!exists($metaentry{':packages'})
8805: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8806: foreach my $key (keys(%packagetab)) {
1.483 albertel 8807: #no specific packages well let's get default then
8808: if ($key!~/^default&/) { next; }
1.488 albertel 8809: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8810: \%metathesekeys);
8811: }
8812: }
1.338 www 8813: # are there custom rights to evaluate
1.599 albertel 8814: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8815:
1.338 www 8816: #
8817: # Importing a rights file here
1.339 albertel 8818: #
8819: unless ($depthcount) {
1.599 albertel 8820: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8821: my $dir=$filename;
8822: $dir=~s|[^/]*$||;
8823: $location=&filelocation($dir,$location);
1.736 albertel 8824: my $rights_metadata =
8825: &metadata($uri,'keys',$location,'_rights',
8826: $depthcount+1);
8827: foreach my $rights (split(',',$rights_metadata)) {
8828: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8829: $metathesekeys{$rights}=1;
1.339 albertel 8830: }
8831: }
8832: }
1.737 albertel 8833: # uniqifiy package listing
8834: my %seen;
8835: my @uniq_packages =
8836: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8837: $metaentry{':packages'} = join(',',@uniq_packages);
8838:
8839: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8840: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8841: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8842: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8843: # this is the end of "was not already recently cached
1.71 www 8844: }
1.599 albertel 8845: return $metaentry{':'.$what};
1.261 albertel 8846: }
8847:
1.488 albertel 8848: sub metadata_create_package_def {
1.483 albertel 8849: my ($uri,$key,$package,$metathesekeys)=@_;
8850: my ($pack,$name,$subp)=split(/\&/,$key);
8851: if ($subp eq 'default') { next; }
8852:
1.599 albertel 8853: if (defined($metaentry{':packages'})) {
8854: $metaentry{':packages'}.=','.$package;
1.483 albertel 8855: } else {
1.599 albertel 8856: $metaentry{':packages'}=$package;
1.483 albertel 8857: }
8858: my $value=$packagetab{$key};
8859: my $unikey;
8860: $unikey='parameter_0_'.$name;
1.599 albertel 8861: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8862: $$metathesekeys{$unikey}=1;
1.599 albertel 8863: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8864: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8865: }
1.599 albertel 8866: if (defined($metaentry{':'.$unikey.'.default'})) {
8867: $metaentry{':'.$unikey}=
8868: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8869: }
8870: }
8871:
1.261 albertel 8872: sub metadata_generate_part0 {
8873: my ($metadata,$metacache,$uri) = @_;
8874: my %allnames;
1.737 albertel 8875: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8876: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8877: my $part=$$metacache{':'.$metakey.'.part'};
8878: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8879: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8880: $allnames{$name}=$part;
8881: }
8882: }
8883: }
8884: foreach my $name (keys(%allnames)) {
8885: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8886: my $key=":parameter_0_$name";
1.261 albertel 8887: $$metacache{"$key.part"}='0';
8888: $$metacache{"$key.name"}=$name;
1.428 albertel 8889: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8890: $allnames{$name}.'_'.$name.
8891: '.type'};
1.428 albertel 8892: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8893: '.display'};
1.644 www 8894: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8895: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8896: $$metacache{"$key.display"}=$olddis;
8897: }
1.71 www 8898: }
8899:
1.764 albertel 8900: # ------------------------------------------------------ Devalidate title cache
8901:
8902: sub devalidate_title_cache {
8903: my ($url)=@_;
8904: if (!$env{'request.course.id'}) { return; }
8905: my $symb=&symbread($url);
8906: if (!$symb) { return; }
8907: my $key=$env{'request.course.id'}."\0".$symb;
8908: &devalidate_cache_new('title',$key);
8909: }
8910:
1.1014 droeschl 8911: # ------------------------------------------------- Get the title of a course
8912:
8913: sub current_course_title {
8914: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8915: }
1.301 www 8916: # ------------------------------------------------- Get the title of a resource
8917:
8918: sub gettitle {
8919: my $urlsymb=shift;
8920: my $symb=&symbread($urlsymb);
1.534 albertel 8921: if ($symb) {
1.620 albertel 8922: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8923: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8924: if (defined($cached)) {
8925: return $result;
8926: }
1.534 albertel 8927: my ($map,$resid,$url)=&decode_symb($symb);
8928: my $title='';
1.907 albertel 8929: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8930: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8931: } else {
8932: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8933: &GDBM_READER(),0640)) {
8934: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8935: $title=$bighash{'title_'.$mapid.'.'.$resid};
8936: untie(%bighash);
8937: }
1.534 albertel 8938: }
8939: $title=~s/\&colon\;/\:/gs;
8940: if ($title) {
1.599 albertel 8941: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8942: }
8943: $urlsymb=$url;
8944: }
8945: my $title=&metadata($urlsymb,'title');
8946: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8947: return $title;
1.301 www 8948: }
1.613 albertel 8949:
1.614 albertel 8950: sub get_slot {
8951: my ($which,$cnum,$cdom)=@_;
8952: if (!$cnum || !$cdom) {
1.790 albertel 8953: (undef,my $courseid)=&whichuser();
1.620 albertel 8954: $cdom=$env{'course.'.$courseid.'.domain'};
8955: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8956: }
1.703 albertel 8957: my $key=join("\0",'slots',$cdom,$cnum,$which);
8958: my %slotinfo;
8959: if (exists($remembered{$key})) {
8960: $slotinfo{$which} = $remembered{$key};
8961: } else {
8962: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8963: &Apache::lonhomework::showhash(%slotinfo);
8964: my ($tmp)=keys(%slotinfo);
8965: if ($tmp=~/^error:/) { return (); }
8966: $remembered{$key} = $slotinfo{$which};
8967: }
1.616 albertel 8968: if (ref($slotinfo{$which}) eq 'HASH') {
8969: return %{$slotinfo{$which}};
8970: }
8971: return $slotinfo{$which};
1.614 albertel 8972: }
1.31 www 8973: # ------------------------------------------------- Update symbolic store links
8974:
8975: sub symblist {
8976: my ($mapname,%newhash)=@_;
1.438 www 8977: $mapname=&deversion(&declutter($mapname));
1.31 www 8978: my %hash;
1.620 albertel 8979: if (($env{'request.course.fn'}) && (%newhash)) {
8980: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8981: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8982: foreach my $url (keys(%newhash)) {
1.711 albertel 8983: next if ($url eq 'last_known'
8984: && $env{'form.no_update_last_known'});
8985: $hash{declutter($url)}=&encode_symb($mapname,
8986: $newhash{$url}->[1],
8987: $newhash{$url}->[0]);
1.191 harris41 8988: }
1.31 www 8989: if (untie(%hash)) {
8990: return 'ok';
8991: }
8992: }
8993: }
8994: return 'error';
1.212 www 8995: }
8996:
8997: # --------------------------------------------------------------- Verify a symb
8998:
8999: sub symbverify {
1.510 www 9000: my ($symb,$thisurl)=@_;
9001: my $thisfn=$thisurl;
1.439 www 9002: $thisfn=&declutter($thisfn);
1.215 www 9003: # direct jump to resource in page or to a sequence - will construct own symbs
9004: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9005: # check URL part
1.409 www 9006: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9007:
1.431 www 9008: unless ($url eq $thisfn) { return 0; }
1.213 www 9009:
1.216 www 9010: $symb=&symbclean($symb);
1.510 www 9011: $thisurl=&deversion($thisurl);
1.439 www 9012: $thisfn=&deversion($thisfn);
1.213 www 9013:
9014: my %bighash;
9015: my $okay=0;
1.431 www 9016:
1.620 albertel 9017: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9018: &GDBM_READER(),0640)) {
1.1032 raeburn 9019: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9020: $thisurl =~ s/\?.+$//;
9021: }
1.510 www 9022: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 9023: unless ($ids) {
1.1056.4.21 raeburn 9024: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9025: $ids=$bighash{$idkey};
1.216 www 9026: }
9027: if ($ids) {
9028: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9029: foreach my $id (split(/\,/,$ids)) {
9030: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9031: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9032: $symb =~ s/\?.+$//;
9033: }
1.216 www 9034: if (
9035: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9036: eq $symb) {
1.620 albertel 9037: if (($env{'request.role.adv'}) ||
1.1056.4.20 raeburn 9038: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9039: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9040: $okay=1;
9041: }
9042: }
1.216 www 9043: }
9044: }
1.213 www 9045: untie(%bighash);
9046: }
9047: return $okay;
1.31 www 9048: }
9049:
1.210 www 9050: # --------------------------------------------------------------- Clean-up symb
9051:
9052: sub symbclean {
9053: my $symb=shift;
1.568 albertel 9054: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9055: # remove version from map
9056: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9057:
1.210 www 9058: # remove version from URL
9059: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9060:
1.507 www 9061: # remove wrapper
9062:
1.510 www 9063: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9064: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9065: return $symb;
1.409 www 9066: }
9067:
9068: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9069:
9070: sub encode_symb {
9071: my ($map,$resid,$url)=@_;
9072: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9073: }
1.409 www 9074:
9075: sub decode_symb {
1.568 albertel 9076: my $symb=shift;
9077: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9078: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9079: return (&fixversion($map),$resid,&fixversion($url));
9080: }
9081:
9082: sub fixversion {
9083: my $fn=shift;
1.609 banghart 9084: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9085: my %bighash;
9086: my $uri=&clutter($fn);
1.620 albertel 9087: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9088: # is this cached?
1.599 albertel 9089: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9090: if (defined($cached)) { return $result; }
9091: # unfortunately not cached, or expired
1.620 albertel 9092: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9093: &GDBM_READER(),0640)) {
9094: if ($bighash{'version_'.$uri}) {
9095: my $version=$bighash{'version_'.$uri};
1.444 www 9096: unless (($version eq 'mostrecent') ||
9097: ($version==&getversion($uri))) {
1.440 www 9098: $uri=~s/\.(\w+)$/\.$version\.$1/;
9099: }
9100: }
9101: untie %bighash;
1.413 www 9102: }
1.599 albertel 9103: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9104: }
9105:
9106: sub deversion {
9107: my $url=shift;
9108: $url=~s/\.\d+\.(\w+)$/\.$1/;
9109: return $url;
1.210 www 9110: }
9111:
1.31 www 9112: # ------------------------------------------------------ Return symb list entry
9113:
9114: sub symbread {
1.249 www 9115: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9116: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9117: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9118: # no filename provided? try from environment
1.44 www 9119: unless ($thisfn) {
1.620 albertel 9120: if ($env{'request.symb'}) {
9121: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9122: }
1.620 albertel 9123: $thisfn=$env{'request.filename'};
1.44 www 9124: }
1.569 albertel 9125: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9126: # is that filename actually a symb? Verify, clean, and return
9127: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9128: if (&symbverify($thisfn,$1)) {
1.620 albertel 9129: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9130: }
1.242 www 9131: }
1.44 www 9132: $thisfn=declutter($thisfn);
1.31 www 9133: my %hash;
1.37 www 9134: my %bighash;
9135: my $syval='';
1.620 albertel 9136: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9137: my $targetfn = $thisfn;
1.609 banghart 9138: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9139: $targetfn = 'adm/wrapper/'.$thisfn;
9140: }
1.687 albertel 9141: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9142: $targetfn=$1;
9143: }
1.620 albertel 9144: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9145: &GDBM_READER(),0640)) {
1.481 raeburn 9146: $syval=$hash{$targetfn};
1.37 www 9147: untie(%hash);
9148: }
9149: # ---------------------------------------------------------- There was an entry
9150: if ($syval) {
1.601 albertel 9151: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9152: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9153: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9154: #return $env{$cache_str}='';
1.601 albertel 9155: #}
9156: #$syval.=$1;
9157: #}
1.37 www 9158: } else {
9159: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9160: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9161: &GDBM_READER(),0640)) {
1.37 www 9162: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9163: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9164: unless ($ids) {
9165: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9166: }
9167: unless ($ids) {
9168: # alias?
9169: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9170: }
1.37 www 9171: if ($ids) {
9172: # ------------------------------------------------------------------- Has ID(s)
9173: my @possibilities=split(/\,/,$ids);
1.39 www 9174: if ($#possibilities==0) {
9175: # ----------------------------------------------- There is only one possibility
1.37 www 9176: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9177: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9178: $resid,$thisfn);
1.249 www 9179: } elsif (!$donotrecurse) {
1.39 www 9180: # ------------------------------------------ There is more than one possibility
9181: my $realpossible=0;
1.800 albertel 9182: foreach my $id (@possibilities) {
9183: my $file=$bighash{'src_'.$id};
1.39 www 9184: if (&allowed('bre',$file)) {
1.800 albertel 9185: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9186: if ($bighash{'map_type_'.$mapid} ne 'page') {
9187: $realpossible++;
1.626 albertel 9188: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9189: $resid,$thisfn);
1.39 www 9190: }
9191: }
1.191 harris41 9192: }
1.39 www 9193: if ($realpossible!=1) { $syval=''; }
1.249 www 9194: } else {
9195: $syval='';
1.37 www 9196: }
9197: }
9198: untie(%bighash)
1.481 raeburn 9199: }
1.31 www 9200: }
1.62 www 9201: if ($syval) {
1.620 albertel 9202: return $env{$cache_str}=$syval;
1.62 www 9203: }
1.31 www 9204: }
1.949 raeburn 9205: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9206: return $env{$cache_str}='';
1.31 www 9207: }
9208:
9209: # ---------------------------------------------------------- Return random seed
9210:
1.32 www 9211: sub numval {
9212: my $txt=shift;
9213: $txt=~tr/A-J/0-9/;
9214: $txt=~tr/a-j/0-9/;
9215: $txt=~tr/K-T/0-9/;
9216: $txt=~tr/k-t/0-9/;
9217: $txt=~tr/U-Z/0-5/;
9218: $txt=~tr/u-z/0-5/;
9219: $txt=~s/\D//g;
1.564 albertel 9220: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9221: return int($txt);
1.368 albertel 9222: }
9223:
1.484 albertel 9224: sub numval2 {
9225: my $txt=shift;
9226: $txt=~tr/A-J/0-9/;
9227: $txt=~tr/a-j/0-9/;
9228: $txt=~tr/K-T/0-9/;
9229: $txt=~tr/k-t/0-9/;
9230: $txt=~tr/U-Z/0-5/;
9231: $txt=~tr/u-z/0-5/;
9232: $txt=~s/\D//g;
9233: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9234: my $total;
9235: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9236: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9237: return int($total);
9238: }
9239:
1.575 albertel 9240: sub numval3 {
9241: use integer;
9242: my $txt=shift;
9243: $txt=~tr/A-J/0-9/;
9244: $txt=~tr/a-j/0-9/;
9245: $txt=~tr/K-T/0-9/;
9246: $txt=~tr/k-t/0-9/;
9247: $txt=~tr/U-Z/0-5/;
9248: $txt=~tr/u-z/0-5/;
9249: $txt=~s/\D//g;
9250: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9251: my $total;
9252: foreach my $val (@txts) { $total+=$val; }
9253: if ($_64bit) { $total=(($total<<32)>>32); }
9254: return $total;
9255: }
9256:
1.675 albertel 9257: sub digest {
9258: my ($data)=@_;
9259: my $digest=&Digest::MD5::md5($data);
9260: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9261: my ($e,$f);
9262: {
9263: use integer;
9264: $e=($a+$b);
9265: $f=($c+$d);
9266: if ($_64bit) {
9267: $e=(($e<<32)>>32);
9268: $f=(($f<<32)>>32);
9269: }
9270: }
9271: if (wantarray) {
9272: return ($e,$f);
9273: } else {
9274: my $g;
9275: {
9276: use integer;
9277: $g=($e+$f);
9278: if ($_64bit) {
9279: $g=(($g<<32)>>32);
9280: }
9281: }
9282: return $g;
9283: }
9284: }
9285:
1.368 albertel 9286: sub latest_rnd_algorithm_id {
1.675 albertel 9287: return '64bit5';
1.366 albertel 9288: }
1.32 www 9289:
1.503 albertel 9290: sub get_rand_alg {
9291: my ($courseid)=@_;
1.790 albertel 9292: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9293: if ($courseid) {
1.620 albertel 9294: return $env{"course.$courseid.rndseed"};
1.503 albertel 9295: }
9296: return &latest_rnd_algorithm_id();
9297: }
9298:
1.562 albertel 9299: sub validCODE {
9300: my ($CODE)=@_;
9301: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9302: return 0;
9303: }
9304:
1.491 albertel 9305: sub getCODE {
1.620 albertel 9306: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9307: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9308: defined($Apache::lonhomework::parsing_a_task) ) &&
9309: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9310: return $Apache::lonhomework::history{'resource.CODE'};
9311: }
9312: return undef;
9313: }
9314:
1.31 www 9315: sub rndseed {
1.155 albertel 9316: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9317: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9318: if (!defined($symb)) {
1.366 albertel 9319: unless ($symb=$wsymb) { return time; }
9320: }
9321: if (!$courseid) { $courseid=$wcourseid; }
9322: if (!$domain) { $domain=$wdomain; }
9323: if (!$username) { $username=$wusername }
1.503 albertel 9324: my $which=&get_rand_alg();
1.803 albertel 9325:
1.491 albertel 9326: if (defined(&getCODE())) {
1.675 albertel 9327: if ($which eq '64bit5') {
9328: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9329: } elsif ($which eq '64bit4') {
1.575 albertel 9330: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9331: } else {
9332: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9333: }
1.675 albertel 9334: } elsif ($which eq '64bit5') {
9335: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9336: } elsif ($which eq '64bit4') {
9337: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9338: } elsif ($which eq '64bit3') {
9339: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9340: } elsif ($which eq '64bit2') {
9341: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9342: } elsif ($which eq '64bit') {
9343: return &rndseed_64bit($symb,$courseid,$domain,$username);
9344: }
9345: return &rndseed_32bit($symb,$courseid,$domain,$username);
9346: }
9347:
9348: sub rndseed_32bit {
9349: my ($symb,$courseid,$domain,$username)=@_;
9350: {
9351: use integer;
9352: my $symbchck=unpack("%32C*",$symb) << 27;
9353: my $symbseed=numval($symb) << 22;
9354: my $namechck=unpack("%32C*",$username) << 17;
9355: my $nameseed=numval($username) << 12;
9356: my $domainseed=unpack("%32C*",$domain) << 7;
9357: my $courseseed=unpack("%32C*",$courseid);
9358: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9359: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9360: #&logthis("rndseed :$num:$symb");
1.564 albertel 9361: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9362: return $num;
9363: }
9364: }
9365:
9366: sub rndseed_64bit {
9367: my ($symb,$courseid,$domain,$username)=@_;
9368: {
9369: use integer;
9370: my $symbchck=unpack("%32S*",$symb) << 21;
9371: my $symbseed=numval($symb) << 10;
9372: my $namechck=unpack("%32S*",$username);
9373:
9374: my $nameseed=numval($username) << 21;
9375: my $domainseed=unpack("%32S*",$domain) << 10;
9376: my $courseseed=unpack("%32S*",$courseid);
9377:
9378: my $num1=$symbchck+$symbseed+$namechck;
9379: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9380: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9381: #&logthis("rndseed :$num:$symb");
1.564 albertel 9382: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9383: return "$num1,$num2";
1.155 albertel 9384: }
1.366 albertel 9385: }
9386:
1.443 albertel 9387: sub rndseed_64bit2 {
9388: my ($symb,$courseid,$domain,$username)=@_;
9389: {
9390: use integer;
9391: # strings need to be an even # of cahracters long, it it is odd the
9392: # last characters gets thrown away
9393: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9394: my $symbseed=numval($symb) << 10;
9395: my $namechck=unpack("%32S*",$username.' ');
9396:
9397: my $nameseed=numval($username) << 21;
1.501 albertel 9398: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9399: my $courseseed=unpack("%32S*",$courseid.' ');
9400:
9401: my $num1=$symbchck+$symbseed+$namechck;
9402: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9403: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9404: #&logthis("rndseed :$num:$symb");
1.803 albertel 9405: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9406: return "$num1,$num2";
9407: }
9408: }
9409:
9410: sub rndseed_64bit3 {
9411: my ($symb,$courseid,$domain,$username)=@_;
9412: {
9413: use integer;
9414: # strings need to be an even # of cahracters long, it it is odd the
9415: # last characters gets thrown away
9416: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9417: my $symbseed=numval2($symb) << 10;
9418: my $namechck=unpack("%32S*",$username.' ');
9419:
9420: my $nameseed=numval2($username) << 21;
1.443 albertel 9421: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9422: my $courseseed=unpack("%32S*",$courseid.' ');
9423:
9424: my $num1=$symbchck+$symbseed+$namechck;
9425: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9426: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9427: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9428: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9429:
1.503 albertel 9430: return "$num1:$num2";
1.443 albertel 9431: }
9432: }
9433:
1.575 albertel 9434: sub rndseed_64bit4 {
9435: my ($symb,$courseid,$domain,$username)=@_;
9436: {
9437: use integer;
9438: # strings need to be an even # of cahracters long, it it is odd the
9439: # last characters gets thrown away
9440: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9441: my $symbseed=numval3($symb) << 10;
9442: my $namechck=unpack("%32S*",$username.' ');
9443:
9444: my $nameseed=numval3($username) << 21;
9445: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9446: my $courseseed=unpack("%32S*",$courseid.' ');
9447:
9448: my $num1=$symbchck+$symbseed+$namechck;
9449: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9450: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9451: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9452: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9453:
9454: return "$num1:$num2";
9455: }
9456: }
9457:
1.675 albertel 9458: sub rndseed_64bit5 {
9459: my ($symb,$courseid,$domain,$username)=@_;
9460: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9461: return "$num1:$num2";
9462: }
9463:
1.366 albertel 9464: sub rndseed_CODE_64bit {
9465: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9466: {
1.366 albertel 9467: use integer;
1.443 albertel 9468: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9469: my $symbseed=numval2($symb);
1.491 albertel 9470: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9471: my $CODEseed=numval(&getCODE());
1.443 albertel 9472: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9473: my $num1=$symbseed+$CODEchck;
9474: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9475: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9476: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9477: if ($_64bit) { $num1=(($num1<<32)>>32); }
9478: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9479: return "$num1:$num2";
1.366 albertel 9480: }
9481: }
9482:
1.575 albertel 9483: sub rndseed_CODE_64bit4 {
9484: my ($symb,$courseid,$domain,$username)=@_;
9485: {
9486: use integer;
9487: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9488: my $symbseed=numval3($symb);
9489: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9490: my $CODEseed=numval3(&getCODE());
9491: my $courseseed=unpack("%32S*",$courseid.' ');
9492: my $num1=$symbseed+$CODEchck;
9493: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9494: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9495: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9496: if ($_64bit) { $num1=(($num1<<32)>>32); }
9497: if ($_64bit) { $num2=(($num2<<32)>>32); }
9498: return "$num1:$num2";
9499: }
9500: }
9501:
1.675 albertel 9502: sub rndseed_CODE_64bit5 {
9503: my ($symb,$courseid,$domain,$username)=@_;
9504: my $code = &getCODE();
9505: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9506: return "$num1:$num2";
9507: }
9508:
1.366 albertel 9509: sub setup_random_from_rndseed {
9510: my ($rndseed)=@_;
1.503 albertel 9511: if ($rndseed =~/([,:])/) {
9512: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9513: &Math::Random::random_set_seed(abs($num1),abs($num2));
9514: } else {
9515: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9516: }
1.36 albertel 9517: }
9518:
1.474 albertel 9519: sub latest_receipt_algorithm_id {
1.835 albertel 9520: return 'receipt3';
1.474 albertel 9521: }
9522:
1.480 www 9523: sub recunique {
9524: my $fucourseid=shift;
9525: my $unique;
1.835 albertel 9526: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9527: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9528: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9529: } else {
9530: $unique=$perlvar{'lonReceipt'};
9531: }
9532: return unpack("%32C*",$unique);
9533: }
9534:
9535: sub recprefix {
9536: my $fucourseid=shift;
9537: my $prefix;
1.835 albertel 9538: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9539: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9540: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9541: } else {
9542: $prefix=$perlvar{'lonHostID'};
9543: }
9544: return unpack("%32C*",$prefix);
9545: }
9546:
1.76 www 9547: sub ireceipt {
1.474 albertel 9548: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9549:
9550: my $return =&recprefix($fucourseid).'-';
9551:
9552: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9553: $env{'request.state'} eq 'construct') {
9554: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9555: return $return;
9556: }
9557:
1.76 www 9558: my $cuname=unpack("%32C*",$funame);
9559: my $cudom=unpack("%32C*",$fudom);
9560: my $cucourseid=unpack("%32C*",$fucourseid);
9561: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9562: my $cunique=&recunique($fucourseid);
1.474 albertel 9563: my $cpart=unpack("%32S*",$part);
1.835 albertel 9564: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9565:
1.790 albertel 9566: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9567:
9568: $return.= ($cunique%$cuname+
9569: $cunique%$cudom+
9570: $cusymb%$cuname+
9571: $cusymb%$cudom+
9572: $cucourseid%$cuname+
9573: $cucourseid%$cudom+
9574: $cpart%$cuname+
9575: $cpart%$cudom);
9576: } else {
9577: $return.= ($cunique%$cuname+
9578: $cunique%$cudom+
9579: $cusymb%$cuname+
9580: $cusymb%$cudom+
9581: $cucourseid%$cuname+
9582: $cucourseid%$cudom);
9583: }
9584: return $return;
1.76 www 9585: }
9586:
9587: sub receipt {
1.474 albertel 9588: my ($part)=@_;
1.790 albertel 9589: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9590: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9591: }
1.260 ng 9592:
1.790 albertel 9593: sub whichuser {
9594: my ($passedsymb)=@_;
9595: my ($symb,$courseid,$domain,$name,$publicuser);
9596: if (defined($env{'form.grade_symb'})) {
9597: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9598: my $allowed=&allowed('vgr',$tmp_courseid);
9599: if (!$allowed &&
9600: exists($env{'request.course.sec'}) &&
9601: $env{'request.course.sec'} !~ /^\s*$/) {
9602: $allowed=&allowed('vgr',$tmp_courseid.
9603: '/'.$env{'request.course.sec'});
9604: }
9605: if ($allowed) {
9606: ($symb)=&get_env_multiple('form.grade_symb');
9607: $courseid=$tmp_courseid;
9608: ($domain)=&get_env_multiple('form.grade_domain');
9609: ($name)=&get_env_multiple('form.grade_username');
9610: return ($symb,$courseid,$domain,$name,$publicuser);
9611: }
9612: }
9613: if (!$passedsymb) {
9614: $symb=&symbread();
9615: } else {
9616: $symb=$passedsymb;
9617: }
9618: $courseid=$env{'request.course.id'};
9619: $domain=$env{'user.domain'};
9620: $name=$env{'user.name'};
9621: if ($name eq 'public' && $domain eq 'public') {
9622: if (!defined($env{'form.username'})) {
9623: $env{'form.username'}.=time.rand(10000000);
9624: }
9625: $name.=$env{'form.username'};
9626: }
9627: return ($symb,$courseid,$domain,$name,$publicuser);
9628:
9629: }
9630:
1.36 albertel 9631: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9632: # returns either the contents of the file or
9633: # -1 if the file doesn't exist
1.481 raeburn 9634: #
9635: # if the target is a file that was uploaded via DOCS,
9636: # a check will be made to see if a current copy exists on the local server,
9637: # if it does this will be served, otherwise a copy will be retrieved from
9638: # the home server for the course and stored in /home/httpd/html/userfiles on
9639: # the local server.
1.472 albertel 9640:
1.36 albertel 9641: sub getfile {
1.538 albertel 9642: my ($file) = @_;
1.609 banghart 9643: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9644: &repcopy($file);
9645: return &readfile($file);
9646: }
9647:
9648: sub repcopy_userfile {
9649: my ($file)=@_;
1.609 banghart 9650: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9651: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9652: my ($cdom,$cnum,$filename) =
1.811 albertel 9653: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9654: my $uri="/uploaded/$cdom/$cnum/$filename";
9655: if (-e "$file") {
1.828 www 9656: # we already have a local copy, check it out
1.538 albertel 9657: my @fileinfo = stat($file);
1.828 www 9658: my $rtncode;
9659: my $info;
1.538 albertel 9660: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9661: if ($lwpresp ne 'ok') {
1.828 www 9662: # there is no such file anymore, even though we had a local copy
1.482 albertel 9663: if ($rtncode eq '404') {
1.538 albertel 9664: unlink($file);
1.482 albertel 9665: }
9666: return -1;
9667: }
9668: if ($info < $fileinfo[9]) {
1.828 www 9669: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9670: return 'ok';
1.828 www 9671: } else {
9672: # the file is outdated, get rid of it
9673: unlink($file);
1.482 albertel 9674: }
1.828 www 9675: }
9676: # one way or the other, at this point, we don't have the file
9677: # construct the correct path for the file
9678: my @parts = ($cdom,$cnum);
9679: if ($filename =~ m|^(.+)/[^/]+$|) {
9680: push @parts, split(/\//,$1);
9681: }
9682: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9683: foreach my $part (@parts) {
9684: $path .= '/'.$part;
9685: if (!-e $path) {
9686: mkdir($path,0770);
1.482 albertel 9687: }
9688: }
1.828 www 9689: # now the path exists for sure
9690: # get a user agent
9691: my $ua=new LWP::UserAgent;
9692: my $transferfile=$file.'.in.transfer';
9693: # FIXME: this should flock
9694: if (-e $transferfile) { return 'ok'; }
9695: my $request;
9696: $uri=~s/^\///;
1.980 raeburn 9697: my $homeserver = &homeserver($cnum,$cdom);
9698: my $protocol = $protocol{$homeserver};
9699: $protocol = 'http' if ($protocol ne 'https');
9700: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9701: my $response=$ua->request($request,$transferfile);
9702: # did it work?
9703: if ($response->is_error()) {
9704: unlink($transferfile);
9705: &logthis("Userfile repcopy failed for $uri");
9706: return -1;
9707: }
9708: # worked, rename the transfer file
9709: rename($transferfile,$file);
1.607 raeburn 9710: return 'ok';
1.481 raeburn 9711: }
9712:
1.517 albertel 9713: sub tokenwrapper {
9714: my $uri=shift;
1.980 raeburn 9715: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9716: $uri=~s|^/||;
1.620 albertel 9717: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9718: my $token=$1;
1.552 albertel 9719: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9720: if ($udom && $uname && $file) {
9721: $file=~s|(\?\.*)*$||;
1.949 raeburn 9722: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9723: my $homeserver = &homeserver($uname,$udom);
9724: my $protocol = $protocol{$homeserver};
9725: $protocol = 'http' if ($protocol ne 'https');
9726: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9727: (($uri=~/\?/)?'&':'?').'token='.$token.
9728: '&tokenissued='.$perlvar{'lonHostID'};
9729: } else {
9730: return '/adm/notfound.html';
9731: }
9732: }
9733:
1.828 www 9734: # call with reqtype HEAD: get last modification time
9735: # call with reqtype GET: get the file contents
9736: # Do not call this with reqtype GET for large files! It loads everything into memory
9737: #
1.481 raeburn 9738: sub getuploaded {
9739: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9740: $uri=~s/^\///;
1.980 raeburn 9741: my $homeserver = &homeserver($cnum,$cdom);
9742: my $protocol = $protocol{$homeserver};
9743: $protocol = 'http' if ($protocol ne 'https');
9744: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9745: my $ua=new LWP::UserAgent;
9746: my $request=new HTTP::Request($reqtype,$uri);
9747: my $response=$ua->request($request);
9748: $$rtncode = $response->code;
1.482 albertel 9749: if (! $response->is_success()) {
9750: return 'failed';
9751: }
9752: if ($reqtype eq 'HEAD') {
1.486 www 9753: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9754: } elsif ($reqtype eq 'GET') {
9755: $$info = $response->content;
1.472 albertel 9756: }
1.482 albertel 9757: return 'ok';
1.36 albertel 9758: }
9759:
1.481 raeburn 9760: sub readfile {
9761: my $file = shift;
9762: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9763: my $fh;
9764: open($fh,"<$file");
9765: my $a='';
1.800 albertel 9766: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9767: return $a;
9768: }
9769:
1.36 albertel 9770: sub filelocation {
1.590 banghart 9771: my ($dir,$file) = @_;
9772: my $location;
9773: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9774:
9775: if ($file =~ m-^/adm/-) {
9776: $file=~s-^/adm/wrapper/-/-;
9777: $file=~s-^/adm/coursedocs/showdoc/-/-;
9778: }
1.882 albertel 9779:
1.590 banghart 9780: if ($file=~m:^/~:) { # is a contruction space reference
9781: $location = $file;
9782: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9783: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9784: # is a correct contruction space reference
9785: $location = $file;
1.956 raeburn 9786: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9787: $location = $file;
1.609 banghart 9788: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9789: my ($udom,$uname,$filename)=
1.811 albertel 9790: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9791: my $home=&homeserver($uname,$udom);
9792: my $is_me=0;
9793: my @ids=¤t_machine_ids();
9794: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9795: if ($is_me) {
1.955 raeburn 9796: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9797: } else {
9798: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9799: $udom.'/'.$uname.'/'.$filename;
9800: }
1.882 albertel 9801: } elsif ($file =~ m-^/adm/-) {
9802: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9803: } else {
9804: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9805: $file=~s:^/res/:/:;
9806: if ( !( $file =~ m:^/:) ) {
9807: $location = $dir. '/'.$file;
9808: } else {
9809: $location = '/home/httpd/html/res'.$file;
9810: }
1.59 albertel 9811: }
1.590 banghart 9812: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9813: while ($location=~m{/\.\./}) {
9814: if ($location =~ m{/[^/]+/\.\./}) {
9815: $location=~ s{/[^/]+/\.\./}{/}g;
9816: } else {
9817: $location=~ s{/\.\./}{/}g;
9818: }
9819: } #remove dir/..
1.590 banghart 9820: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9821: return $location;
1.46 www 9822: }
1.36 albertel 9823:
1.46 www 9824: sub hreflocation {
9825: my ($dir,$file)=@_;
1.980 raeburn 9826: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9827: $file=filelocation($dir,$file);
1.700 albertel 9828: } elsif ($file=~m-^/adm/-) {
9829: $file=~s-^/adm/wrapper/-/-;
9830: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9831: }
9832: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9833: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9834: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9835: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9836: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9837: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9838: -/uploaded/$1/$2/-x;
1.46 www 9839: }
1.913 albertel 9840: if ($file=~ m{^/userfiles/}) {
9841: $file =~ s{^/userfiles/}{/uploaded/};
9842: }
1.462 albertel 9843: return $file;
1.465 albertel 9844: }
9845:
9846: sub current_machine_domains {
1.853 albertel 9847: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9848: }
9849:
9850: sub machine_domains {
9851: my ($hostname) = @_;
1.465 albertel 9852: my @domains;
1.838 albertel 9853: my %hostname = &all_hostnames();
1.465 albertel 9854: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9855: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9856: if ($hostname eq $name) {
1.844 albertel 9857: push(@domains,&host_domain($id));
1.465 albertel 9858: }
9859: }
9860: return @domains;
9861: }
9862:
9863: sub current_machine_ids {
1.853 albertel 9864: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9865: }
9866:
9867: sub machine_ids {
9868: my ($hostname) = @_;
9869: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9870: my @ids;
1.888 albertel 9871: my %name_to_host = &all_names();
1.889 albertel 9872: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9873: return @{ $name_to_host{$hostname} };
9874: }
9875: return;
1.31 www 9876: }
9877:
1.824 raeburn 9878: sub additional_machine_domains {
9879: my @domains;
9880: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9881: while( my $line = <$fh>) {
9882: $line =~ s/\s//g;
9883: push(@domains,$line);
9884: }
9885: return @domains;
9886: }
9887:
9888: sub default_login_domain {
9889: my $domain = $perlvar{'lonDefDomain'};
9890: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9891: foreach my $posdom (¤t_machine_domains(),
9892: &additional_machine_domains()) {
9893: if (lc($posdom) eq lc($testdomain)) {
9894: $domain=$posdom;
9895: last;
9896: }
9897: }
9898: return $domain;
9899: }
9900:
1.31 www 9901: # ------------------------------------------------------------- Declutters URLs
9902:
9903: sub declutter {
9904: my $thisfn=shift;
1.569 albertel 9905: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9906: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9907: $thisfn=~s/^\///;
1.697 albertel 9908: $thisfn=~s|^adm/wrapper/||;
9909: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9910: $thisfn=~s/^res\///;
1.1032 raeburn 9911: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9912: $thisfn=~s/\?.+$//;
9913: }
1.268 www 9914: return $thisfn;
9915: }
9916:
9917: # ------------------------------------------------------------- Clutter up URLs
9918:
9919: sub clutter {
9920: my $thisfn='/'.&declutter(shift);
1.887 albertel 9921: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9922: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9923: $thisfn='/res'.$thisfn;
9924: }
1.1031 raeburn 9925: if ($thisfn !~m|^/adm|) {
9926: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9927: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9928: } else {
9929: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9930: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9931: if ($embstyle eq 'ssi'
9932: || ($embstyle eq 'hdn')
9933: || ($embstyle eq 'rat')
9934: || ($embstyle eq 'prv')
9935: || ($embstyle eq 'ign')) {
9936: #do nothing with these
9937: } elsif (($embstyle eq 'img')
1.695 albertel 9938: || ($embstyle eq 'emb')
9939: || ($embstyle eq 'wrp')) {
9940: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9941: } elsif ($embstyle eq 'unk'
9942: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9943: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9944: } else {
1.718 www 9945: # &logthis("Got a blank emb style");
1.695 albertel 9946: }
1.694 albertel 9947: }
9948: }
1.31 www 9949: return $thisfn;
1.12 www 9950: }
9951:
1.787 albertel 9952: sub clutter_with_no_wrapper {
9953: my $uri = &clutter(shift);
9954: if ($uri =~ m-^/adm/-) {
9955: $uri =~ s-^/adm/wrapper/-/-;
9956: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9957: }
9958: return $uri;
9959: }
9960:
1.557 albertel 9961: sub freeze_escape {
9962: my ($value)=@_;
9963: if (ref($value)) {
9964: $value=&nfreeze($value);
9965: return '__FROZEN__'.&escape($value);
9966: }
9967: return &escape($value);
9968: }
9969:
1.11 www 9970:
1.557 albertel 9971: sub thaw_unescape {
9972: my ($value)=@_;
9973: if ($value =~ /^__FROZEN__/) {
9974: substr($value,0,10,undef);
9975: $value=&unescape($value);
9976: return &thaw($value);
9977: }
9978: return &unescape($value);
9979: }
9980:
1.436 albertel 9981: sub correct_line_ends {
9982: my ($result)=@_;
9983: $$result =~s/\r\n/\n/mg;
9984: $$result =~s/\r/\n/mg;
1.415 albertel 9985: }
1.1 albertel 9986: # ================================================================ Main Program
9987:
1.184 www 9988: sub goodbye {
1.204 albertel 9989: &logthis("Starting Shut down");
1.443 albertel 9990: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9991: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9992: #converted
1.599 albertel 9993: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9994: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9995: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9996: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9997: #1.1 only
1.870 albertel 9998: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9999: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10000: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10001: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10002: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10003: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10004: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10005: &flushcourselogs();
10006: &logthis("Shutting down");
10007: }
10008:
1.852 albertel 10009: sub get_dns {
1.869 albertel 10010: my ($url,$func,$ignore_cache) = @_;
10011: if (!$ignore_cache) {
10012: my ($content,$cached)=
10013: &Apache::lonnet::is_cached_new('dns',$url);
10014: if ($cached) {
10015: &$func($content);
10016: return;
10017: }
10018: }
10019:
10020: my %alldns;
1.852 albertel 10021: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10022: foreach my $dns (<$config>) {
10023: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10024: my $line = $1;
10025: my ($host,$protocol) = split(/:/,$line);
10026: if ($protocol ne 'https') {
10027: $protocol = 'http';
10028: }
10029: $alldns{$host} = $protocol;
1.869 albertel 10030: }
10031: while (%alldns) {
10032: my ($dns) = keys(%alldns);
1.852 albertel 10033: my $ua=new LWP::UserAgent;
1.1056.4.33 raeburn 10034: $ua->timeout(30);
1.979 raeburn 10035: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10036: my $response=$ua->request($request);
1.979 raeburn 10037: delete($alldns{$dns});
1.852 albertel 10038: next if ($response->is_error());
10039: my @content = split("\n",$response->content);
1.869 albertel 10040: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10041: &$func(\@content);
1.869 albertel 10042: return;
1.852 albertel 10043: }
10044: close($config);
1.871 albertel 10045: my $which = (split('/',$url))[3];
10046: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10047: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10048: my @content = <$config>;
10049: &$func(\@content);
10050: return;
1.852 albertel 10051: }
1.327 albertel 10052: # ------------------------------------------------------------ Read domain file
10053: {
1.852 albertel 10054: my $loaded;
1.846 albertel 10055: my %domain;
10056:
1.852 albertel 10057: sub parse_domain_tab {
10058: my ($lines) = @_;
10059: foreach my $line (@$lines) {
10060: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10061:
1.846 albertel 10062: chomp($line);
1.852 albertel 10063: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10064: my %this_domain;
10065: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10066: 'lang_def', 'city', 'longi', 'lati',
10067: 'primary') {
10068: $this_domain{$field} = shift(@elements);
10069: }
10070: $domain{$name} = \%this_domain;
1.852 albertel 10071: }
10072: }
1.864 albertel 10073:
10074: sub reset_domain_info {
10075: undef($loaded);
10076: undef(%domain);
10077: }
10078:
1.852 albertel 10079: sub load_domain_tab {
1.869 albertel 10080: my ($ignore_cache) = @_;
10081: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10082: my $fh;
10083: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10084: my @lines = <$fh>;
10085: &parse_domain_tab(\@lines);
1.448 albertel 10086: }
1.852 albertel 10087: close($fh);
10088: $loaded = 1;
1.327 albertel 10089: }
1.846 albertel 10090:
10091: sub domain {
1.852 albertel 10092: &load_domain_tab() if (!$loaded);
10093:
1.846 albertel 10094: my ($name,$what) = @_;
10095: return if ( !exists($domain{$name}) );
10096:
10097: if (!$what) {
10098: return $domain{$name}{'description'};
10099: }
10100: return $domain{$name}{$what};
10101: }
1.974 raeburn 10102:
10103: sub domain_info {
10104: &load_domain_tab() if (!$loaded);
10105: return %domain;
10106: }
10107:
1.327 albertel 10108: }
10109:
10110:
1.1 albertel 10111: # ------------------------------------------------------------- Read hosts file
10112: {
1.838 albertel 10113: my %hostname;
1.844 albertel 10114: my %hostdom;
1.845 albertel 10115: my %libserv;
1.852 albertel 10116: my $loaded;
1.888 albertel 10117: my %name_to_host;
1.1056.4.6 raeburn 10118: my %internetdom;
1.1056.4.25 raeburn 10119: my %LC_dns_serv;
1.852 albertel 10120:
10121: sub parse_hosts_tab {
10122: my ($file) = @_;
10123: foreach my $configline (@$file) {
10124: next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25 raeburn 10125: chomp($configline);
10126: if ($configline =~ /^\^/) {
10127: if ($configline =~ /^\^([\w.\-]+)/) {
10128: $LC_dns_serv{$1} = 1;
10129: }
10130: next;
10131: }
1.1056.4.6 raeburn 10132: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10133: $name=~s/\s//g;
10134: if ($id && $domain && $role && $name) {
10135: $hostname{$id}=$name;
1.888 albertel 10136: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10137: $hostdom{$id}=$domain;
10138: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10139: if (defined($protocol)) {
10140: if ($protocol eq 'https') {
10141: $protocol{$id} = $protocol;
10142: } else {
10143: $protocol{$id} = 'http';
10144: }
1.968 raeburn 10145: } else {
1.969 raeburn 10146: $protocol{$id} = 'http';
1.968 raeburn 10147: }
1.1056.4.6 raeburn 10148: if (defined($intdom)) {
10149: $internetdom{$id} = $intdom;
10150: }
1.852 albertel 10151: }
10152: }
10153: }
1.864 albertel 10154:
10155: sub reset_hosts_info {
1.897 albertel 10156: &purge_remembered();
1.864 albertel 10157: &reset_domain_info();
10158: &reset_hosts_ip_info();
1.892 albertel 10159: undef(%name_to_host);
1.864 albertel 10160: undef(%hostname);
10161: undef(%hostdom);
10162: undef(%libserv);
10163: undef($loaded);
10164: }
1.1 albertel 10165:
1.852 albertel 10166: sub load_hosts_tab {
1.869 albertel 10167: my ($ignore_cache) = @_;
10168: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10169: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10170: my @config = <$config>;
10171: &parse_hosts_tab(\@config);
10172: close($config);
10173: $loaded=1;
1.1 albertel 10174: }
1.852 albertel 10175:
1.838 albertel 10176: sub hostname {
1.852 albertel 10177: &load_hosts_tab() if (!$loaded);
10178:
1.838 albertel 10179: my ($lonid) = @_;
10180: return $hostname{$lonid};
10181: }
1.845 albertel 10182:
1.838 albertel 10183: sub all_hostnames {
1.852 albertel 10184: &load_hosts_tab() if (!$loaded);
10185:
1.838 albertel 10186: return %hostname;
10187: }
1.845 albertel 10188:
1.888 albertel 10189: sub all_names {
10190: &load_hosts_tab() if (!$loaded);
10191:
10192: return %name_to_host;
10193: }
10194:
1.974 raeburn 10195: sub all_host_domain {
10196: &load_hosts_tab() if (!$loaded);
10197: return %hostdom;
10198: }
10199:
1.845 albertel 10200: sub is_library {
1.852 albertel 10201: &load_hosts_tab() if (!$loaded);
10202:
1.845 albertel 10203: return exists($libserv{$_[0]});
10204: }
10205:
10206: sub all_library {
1.852 albertel 10207: &load_hosts_tab() if (!$loaded);
10208:
1.845 albertel 10209: return %libserv;
10210: }
10211:
1.1056.4.2 raeburn 10212: sub unique_library {
10213: #2x reverse removes all hostnames that appear more than once
10214: my %unique = reverse &all_library();
10215: return reverse %unique;
10216: }
10217:
1.841 albertel 10218: sub get_servers {
1.852 albertel 10219: &load_hosts_tab() if (!$loaded);
10220:
1.841 albertel 10221: my ($domain,$type) = @_;
10222: my %possible_hosts = ($type eq 'library') ? %libserv
10223: : %hostname;
10224: my %result;
1.842 albertel 10225: if (ref($domain) eq 'ARRAY') {
10226: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10227: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10228: $result{$host} = $hostname;
10229: }
10230: }
10231: } else {
10232: while ( my ($host,$hostname) = each(%possible_hosts)) {
10233: if ($hostdom{$host} eq $domain) {
10234: $result{$host} = $hostname;
10235: }
1.841 albertel 10236: }
10237: }
10238: return %result;
10239: }
1.845 albertel 10240:
1.1056.4.2 raeburn 10241: sub get_unique_servers {
10242: my %unique = reverse &get_servers(@_);
10243: return reverse %unique;
10244: }
10245:
1.844 albertel 10246: sub host_domain {
1.852 albertel 10247: &load_hosts_tab() if (!$loaded);
10248:
1.844 albertel 10249: my ($lonid) = @_;
10250: return $hostdom{$lonid};
10251: }
10252:
1.841 albertel 10253: sub all_domains {
1.852 albertel 10254: &load_hosts_tab() if (!$loaded);
10255:
1.841 albertel 10256: my %seen;
10257: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10258: return @uniq;
10259: }
1.1056.4.3 raeburn 10260:
10261: sub internet_dom {
10262: &load_hosts_tab() if (!$loaded);
10263:
10264: my ($lonid) = @_;
10265: return $internetdom{$lonid};
10266: }
1.1056.4.27 raeburn 10267:
10268: sub is_LC_dns {
10269: &load_hosts_tab() if (!$loaded);
10270:
10271: my ($hostname) = @_;
10272: return exists($LC_dns_serv{$hostname});
10273: }
10274:
1.1 albertel 10275: }
10276:
1.847 albertel 10277: {
10278: my %iphost;
1.856 albertel 10279: my %name_to_ip;
10280: my %lonid_to_ip;
1.869 albertel 10281:
1.847 albertel 10282: sub get_hosts_from_ip {
10283: my ($ip) = @_;
10284: my %iphosts = &get_iphost();
10285: if (ref($iphosts{$ip})) {
10286: return @{$iphosts{$ip}};
10287: }
10288: return;
1.839 albertel 10289: }
1.864 albertel 10290:
10291: sub reset_hosts_ip_info {
10292: undef(%iphost);
10293: undef(%name_to_ip);
10294: undef(%lonid_to_ip);
10295: }
1.856 albertel 10296:
10297: sub get_host_ip {
10298: my ($lonid) = @_;
10299: if (exists($lonid_to_ip{$lonid})) {
10300: return $lonid_to_ip{$lonid};
10301: }
10302: my $name=&hostname($lonid);
10303: my $ip = gethostbyname($name);
10304: return if (!$ip || length($ip) ne 4);
10305: $ip=inet_ntoa($ip);
10306: $name_to_ip{$name} = $ip;
10307: $lonid_to_ip{$lonid} = $ip;
10308: return $ip;
10309: }
1.847 albertel 10310:
10311: sub get_iphost {
1.869 albertel 10312: my ($ignore_cache) = @_;
1.894 albertel 10313:
1.869 albertel 10314: if (!$ignore_cache) {
10315: if (%iphost) {
10316: return %iphost;
10317: }
10318: my ($ip_info,$cached)=
10319: &Apache::lonnet::is_cached_new('iphost','iphost');
10320: if ($cached) {
10321: %iphost = %{$ip_info->[0]};
10322: %name_to_ip = %{$ip_info->[1]};
10323: %lonid_to_ip = %{$ip_info->[2]};
10324: return %iphost;
10325: }
10326: }
1.894 albertel 10327:
10328: # get yesterday's info for fallback
10329: my %old_name_to_ip;
10330: my ($ip_info,$cached)=
10331: &Apache::lonnet::is_cached_new('iphost','iphost');
10332: if ($cached) {
10333: %old_name_to_ip = %{$ip_info->[1]};
10334: }
10335:
1.888 albertel 10336: my %name_to_host = &all_names();
10337: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10338: my $ip;
10339: if (!exists($name_to_ip{$name})) {
10340: $ip = gethostbyname($name);
10341: if (!$ip || length($ip) ne 4) {
1.894 albertel 10342: if (defined($old_name_to_ip{$name})) {
10343: $ip = $old_name_to_ip{$name};
10344: &logthis("Can't find $name defaulting to old $ip");
10345: } else {
10346: &logthis("Name $name no IP found");
10347: next;
10348: }
10349: } else {
10350: $ip=inet_ntoa($ip);
1.847 albertel 10351: }
10352: $name_to_ip{$name} = $ip;
10353: } else {
10354: $ip = $name_to_ip{$name};
1.653 albertel 10355: }
1.888 albertel 10356: foreach my $id (@{ $name_to_host{$name} }) {
10357: $lonid_to_ip{$id} = $ip;
10358: }
10359: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10360: }
1.869 albertel 10361: &Apache::lonnet::do_cache_new('iphost','iphost',
10362: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10363: 48*60*60);
1.869 albertel 10364:
1.847 albertel 10365: return %iphost;
1.598 albertel 10366: }
10367:
1.992 raeburn 10368: #
10369: # Given a DNS returns the loncapa host name for that DNS
10370: #
10371: sub host_from_dns {
10372: my ($dns) = @_;
10373: my @hosts;
10374: my $ip;
10375:
1.993 raeburn 10376: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10377: $ip = $name_to_ip{$dns};
10378: }
10379: if (!$ip) {
10380: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10381: if (length($ip) == 4) {
10382: $ip = &IO::Socket::inet_ntoa($ip);
10383: }
10384: }
10385: if ($ip) {
10386: @hosts = get_hosts_from_ip($ip);
10387: return $hosts[0];
10388: }
10389: return undef;
1.986 foxr 10390: }
1.992 raeburn 10391:
1.1056.4.3 raeburn 10392: sub get_internet_names {
10393: my ($lonid) = @_;
10394: return if ($lonid eq '');
10395: my ($idnref,$cached)=
10396: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10397: if ($cached) {
10398: return $idnref;
10399: }
10400: my $ip = &get_host_ip($lonid);
10401: my @hosts = &get_hosts_from_ip($ip);
10402: my %iphost = &get_iphost();
10403: my (@idns,%seen);
10404: foreach my $id (@hosts) {
10405: my $dom = &host_domain($id);
10406: my $prim_id = &domain($dom,'primary');
10407: my $prim_ip = &get_host_ip($prim_id);
10408: next if ($seen{$prim_ip});
10409: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10410: foreach my $id (@{$iphost{$prim_ip}}) {
10411: my $intdom = &internet_dom($id);
10412: unless (grep(/^\Q$intdom\E$/,@idns)) {
10413: push(@idns,$intdom);
10414: }
10415: }
10416: }
10417: $seen{$prim_ip} = 1;
10418: }
10419: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10420: }
10421:
10422: }
10423:
10424: sub all_loncaparevs {
10425: 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);
1.986 foxr 10426: }
10427:
1.862 albertel 10428: BEGIN {
10429:
10430: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10431: unless ($readit) {
10432: {
10433: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10434: %perlvar = (%perlvar,%{$configvars});
10435: }
10436:
10437:
1.1 albertel 10438: # ------------------------------------------------------ Read spare server file
10439: {
1.448 albertel 10440: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10441:
10442: while (my $configline=<$config>) {
10443: chomp($configline);
1.284 matthew 10444: if ($configline) {
1.784 albertel 10445: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10446: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10447: push(@{ $spareid{$type} }, $host);
1.1 albertel 10448: }
10449: }
1.448 albertel 10450: close($config);
1.1 albertel 10451: }
1.11 www 10452: # ------------------------------------------------------------ Read permissions
10453: {
1.448 albertel 10454: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10455:
10456: while (my $configline=<$config>) {
1.448 albertel 10457: chomp($configline);
10458: if ($configline) {
10459: my ($role,$perm)=split(/ /,$configline);
10460: if ($perm ne '') { $pr{$role}=$perm; }
10461: }
1.11 www 10462: }
1.448 albertel 10463: close($config);
1.11 www 10464: }
10465:
10466: # -------------------------------------------- Read plain texts for permissions
10467: {
1.448 albertel 10468: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10469:
10470: while (my $configline=<$config>) {
1.448 albertel 10471: chomp($configline);
10472: if ($configline) {
1.742 raeburn 10473: my ($short,@plain)=split(/:/,$configline);
10474: %{$prp{$short}} = ();
10475: if (@plain > 0) {
10476: $prp{$short}{'std'} = $plain[0];
10477: for (my $i=1; $i<@plain; $i++) {
10478: $prp{$short}{'alt'.$i} = $plain[$i];
10479: }
10480: }
1.448 albertel 10481: }
1.135 www 10482: }
1.448 albertel 10483: close($config);
1.135 www 10484: }
10485:
10486: # ---------------------------------------------------------- Read package table
10487: {
1.448 albertel 10488: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10489:
10490: while (my $configline=<$config>) {
1.483 albertel 10491: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10492: chomp($configline);
10493: my ($short,$plain)=split(/:/,$configline);
10494: my ($pack,$name)=split(/\&/,$short);
10495: if ($plain ne '') {
10496: $packagetab{$pack.'&'.$name.'&name'}=$name;
10497: $packagetab{$short}=$plain;
10498: }
1.11 www 10499: }
1.448 albertel 10500: close($config);
1.329 matthew 10501: }
10502:
1.1056.4.3 raeburn 10503: # ---------------------------------------------------------- Read loncaparev table
10504: {
10505: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10506: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10507: while (my $configline=<$config>) {
10508: chomp($configline);
10509: my ($hostid,$loncaparev)=split(/:/,$configline);
10510: $loncaparevs{$hostid}=$loncaparev;
10511: }
10512: close($config);
10513: }
10514: }
10515: }
10516:
10517: # ---------------------------------------------------------- Read serverhostID table
10518: {
10519: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10520: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10521: while (my $configline=<$config>) {
10522: chomp($configline);
10523: my ($name,$id)=split(/:/,$configline);
10524: $serverhomeIDs{$name}=$id;
10525: }
10526: close($config);
10527: }
10528: }
10529: }
10530:
1.1056.4.5 raeburn 10531: {
10532: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10533: if (-e $file) {
10534: my $parser = HTML::LCParser->new($file);
10535: while (my $token = $parser->get_token()) {
10536: if ($token->[0] eq 'S') {
10537: my $item = $token->[1];
10538: my $name = $token->[2]{'name'};
10539: my $value = $token->[2]{'value'};
10540: if ($item ne '' && $name ne '' && $value ne '') {
10541: my $release = $parser->get_text();
10542: $release =~ s/(^\s*|\s*$ )//gx;
10543: $needsrelease{$item.':'.$name.':'.$value} = $release;
10544: }
10545: }
10546: }
10547: }
10548: }
10549:
1.1056.4.33 raeburn 10550: # ---------------------------------------------------------- Read managers table
10551: {
10552: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10553: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10554: while (my $configline=<$config>) {
10555: chomp($configline);
10556: next if ($configline =~ /^\#/);
10557: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
10558: $managerstab{$configline} = 1;
10559: }
10560: }
10561: close($config);
10562: }
10563: }
10564: }
10565:
1.329 matthew 10566: # ------------- set up temporary directory
10567: {
10568: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10569:
1.11 www 10570: }
10571:
1.794 albertel 10572: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10573: 'compress_threshold'=> 20_000,
10574: });
1.185 www 10575:
1.281 www 10576: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10577: $dumpcount=0;
1.958 www 10578: $locknum=0;
1.22 www 10579:
1.163 harris41 10580: &logtouch();
1.672 albertel 10581: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10582: $readit=1;
1.564 albertel 10583: {
10584: use integer;
10585: my $test=(2**32)+1;
1.568 albertel 10586: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10587: &logthis(" Detected 64bit platform ($_64bit)");
10588: }
1.195 www 10589: }
1.1 albertel 10590: }
1.179 www 10591:
1.1 albertel 10592: 1;
1.191 harris41 10593: __END__
10594:
1.243 albertel 10595: =pod
10596:
1.191 harris41 10597: =head1 NAME
10598:
1.243 albertel 10599: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10600:
10601: =head1 SYNOPSIS
10602:
1.243 albertel 10603: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10604:
10605: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10606:
1.243 albertel 10607: Common parameters:
10608:
10609: =over 4
10610:
10611: =item *
10612:
10613: $uname : an internal username (if $cname expecting a course Id specifically)
10614:
10615: =item *
10616:
10617: $udom : a domain (if $cdom expecting a course's domain specifically)
10618:
10619: =item *
10620:
10621: $symb : a resource instance identifier
10622:
10623: =item *
10624:
10625: $namespace : the name of a .db file that contains the data needed or
10626: being set.
10627:
10628: =back
10629:
1.394 bowersj2 10630: =head1 OVERVIEW
1.191 harris41 10631:
1.394 bowersj2 10632: lonnet provides subroutines which interact with the
10633: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10634: about classes, users, and resources.
1.243 albertel 10635:
10636: For many of these objects you can also use this to store data about
10637: them or modify them in various ways.
1.191 harris41 10638:
1.394 bowersj2 10639: =head2 Symbs
1.191 harris41 10640:
1.394 bowersj2 10641: To identify a specific instance of a resource, LON-CAPA uses symbols
10642: or "symbs"X<symb>. These identifiers are built from the URL of the
10643: map, the resource number of the resource in the map, and the URL of
10644: the resource itself. The latter is somewhat redundant, but might help
10645: if maps change.
10646:
10647: An example is
10648:
10649: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10650:
10651: The respective map entry is
10652:
10653: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10654: title="Problem 2">
10655: </resource>
10656:
10657: Symbs are used by the random number generator, as well as to store and
10658: restore data specific to a certain instance of for example a problem.
10659:
10660: =head2 Storing And Retrieving Data
10661:
10662: X<store()>X<cstore()>X<restore()>Three of the most important functions
10663: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10664: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10665: is is the non-critical message twin of cstore. These functions are for
10666: handlers to store a perl hash to a user's permanent data space in an
10667: easy manner, and to retrieve it again on another call. It is expected
10668: that a handler would use this once at the beginning to retrieve data,
10669: and then again once at the end to send only the new data back.
10670:
10671: The data is stored in the user's data directory on the user's
10672: homeserver under the ID of the course.
10673:
10674: The hash that is returned by restore will have all of the previous
10675: value for all of the elements of the hash.
10676:
10677: Example:
10678:
10679: #creating a hash
10680: my %hash;
10681: $hash{'foo'}='bar';
10682:
10683: #storing it
10684: &Apache::lonnet::cstore(\%hash);
10685:
10686: #changing a value
10687: $hash{'foo'}='notbar';
10688:
10689: #adding a new value
10690: $hash{'bar'}='foo';
10691: &Apache::lonnet::cstore(\%hash);
10692:
10693: #retrieving the hash
10694: my %history=&Apache::lonnet::restore();
10695:
10696: #print the hash
10697: foreach my $key (sort(keys(%history))) {
10698: print("\%history{$key} = $history{$key}");
10699: }
10700:
10701: Will print out:
1.191 harris41 10702:
1.394 bowersj2 10703: %history{1:foo} = bar
10704: %history{1:keys} = foo:timestamp
10705: %history{1:timestamp} = 990455579
10706: %history{2:bar} = foo
10707: %history{2:foo} = notbar
10708: %history{2:keys} = foo:bar:timestamp
10709: %history{2:timestamp} = 990455580
10710: %history{bar} = foo
10711: %history{foo} = notbar
10712: %history{timestamp} = 990455580
10713: %history{version} = 2
10714:
10715: Note that the special hash entries C<keys>, C<version> and
10716: C<timestamp> were added to the hash. C<version> will be equal to the
10717: total number of versions of the data that have been stored. The
10718: C<timestamp> attribute will be the UNIX time the hash was
10719: stored. C<keys> is available in every historical section to list which
10720: keys were added or changed at a specific historical revision of a
10721: hash.
10722:
10723: B<Warning>: do not store the hash that restore returns directly. This
10724: will cause a mess since it will restore the historical keys as if the
10725: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10726:
1.394 bowersj2 10727: Calling convention:
1.191 harris41 10728:
1.394 bowersj2 10729: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10730: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10731:
1.394 bowersj2 10732: For more detailed information, see lonnet specific documentation.
1.191 harris41 10733:
1.394 bowersj2 10734: =head1 RETURN MESSAGES
1.191 harris41 10735:
1.394 bowersj2 10736: =over 4
1.191 harris41 10737:
1.394 bowersj2 10738: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10739:
1.394 bowersj2 10740: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10741: when the connection is brought back up
1.191 harris41 10742:
1.394 bowersj2 10743: =item * B<con_failed>: unable to contact remote host and unable to save message
10744: for later delivery
1.191 harris41 10745:
1.967 bisitz 10746: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10747:
1.394 bowersj2 10748: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10749: that was requested
1.191 harris41 10750:
1.243 albertel 10751: =back
1.191 harris41 10752:
1.243 albertel 10753: =head1 PUBLIC SUBROUTINES
1.191 harris41 10754:
1.243 albertel 10755: =head2 Session Environment Functions
1.191 harris41 10756:
1.243 albertel 10757: =over 4
1.191 harris41 10758:
1.394 bowersj2 10759: =item *
10760: X<appenv()>
1.949 raeburn 10761: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10762: the user envirnoment file, and will be restored for each access this
1.620 albertel 10763: user makes during this session, also modifies the %env for the current
1.949 raeburn 10764: process. Optional rolesarrayref - if defined contains a reference to an array
10765: of roles which are exempt from the restriction on modifying user.role entries
10766: in the user's environment.db and in %env.
1.191 harris41 10767:
10768: =item *
1.394 bowersj2 10769: X<delenv()>
1.987 raeburn 10770: B<delenv($delthis,$regexp)>: removes all items from the session
10771: environment file that begin with $delthis. If the
10772: optional second arg - $regexp - is true, $delthis is treated as a
10773: regular expression, otherwise \Q$delthis\E is used.
10774: The values are also deleted from the current processes %env.
1.191 harris41 10775:
1.795 albertel 10776: =item * get_env_multiple($name)
10777:
10778: gets $name from the %env hash, it seemlessly handles the cases where multiple
10779: values may be defined and end up as an array ref.
10780:
10781: returns an array of values
10782:
1.243 albertel 10783: =back
10784:
10785: =head2 User Information
1.191 harris41 10786:
1.243 albertel 10787: =over 4
1.191 harris41 10788:
10789: =item *
1.394 bowersj2 10790: X<queryauthenticate()>
10791: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10792: authentication scheme
10793:
10794: =item *
1.394 bowersj2 10795: X<authenticate()>
1.1056.4.3 raeburn 10796: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10797: authenticate user from domain's lib servers (first use the current
10798: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10799: $checkdefauth is optional (value is 1 if a check should be made to
10800: authenticate user using default authentication method, and allow
10801: account creation if username does not have account in the domain).
10802: $clientcancheckhost is optional (value is 1 if checking whether the
10803: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10804:
10805: =item *
1.394 bowersj2 10806: X<homeserver()>
10807: B<homeserver($uname,$udom)>: find the server which has
10808: the user's directory and files (there must be only one), this caches
10809: the answer, and also caches if there is a borken connection.
1.191 harris41 10810:
10811: =item *
1.394 bowersj2 10812: X<idget()>
10813: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10814: (IDs are a unique resource in a domain, there must be only 1 ID per
10815: username, and only 1 username per ID in a specific domain) (returns
10816: hash: id=>name,id=>name)
1.191 harris41 10817:
10818: =item *
1.394 bowersj2 10819: X<idrget()>
10820: B<idrget($udom,@unames)>: find the IDs behind a list of
10821: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10822:
10823: =item *
1.394 bowersj2 10824: X<idput()>
10825: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10826:
10827: =item *
1.394 bowersj2 10828: X<rolesinit()>
10829: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10830:
10831: =item *
1.551 albertel 10832: X<getsection()>
10833: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10834: course $cname, return section name/number or '' for "not in course"
10835: and '-1' for "no section"
10836:
10837: =item *
1.394 bowersj2 10838: X<userenvironment()>
10839: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10840: passed in @what from the requested user's environment, returns a hash
10841:
1.858 raeburn 10842: =item *
10843: X<userlog_query()>
1.859 albertel 10844: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10845: activity.log file. %filters defines filters applied when parsing the
10846: log file. These can be start or end timestamps, or the type of action
10847: - log to look for Login or Logout events, check for Checkin or
10848: Checkout, role for role selection. The response is in the form
10849: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10850: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10851:
1.243 albertel 10852: =back
10853:
10854: =head2 User Roles
10855:
10856: =over 4
10857:
10858: =item *
10859:
1.810 raeburn 10860: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10861: F: full access
10862: U,I,K: authentication modes (cxx only)
10863: '': forbidden
10864: 1: user needs to choose course
10865: 2: browse allowed
1.766 albertel 10866: A: passphrase authentication needed
1.243 albertel 10867:
10868: =item *
10869:
10870: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10871: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10872: and course level
10873:
10874: =item *
10875:
1.988 raeburn 10876: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10877: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10878: $type is Course (default) or Community.
1.988 raeburn 10879: If $forcedefault evaluates to true, text returned will be default
10880: text for $type. Otherwise, if this is a course, the text returned
10881: will be a custom name for the role (if defined in the course's
10882: environment). If no custom name is defined the default is returned.
10883:
1.832 raeburn 10884: =item *
10885:
1.935 raeburn 10886: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10887: All arguments are optional. Returns a hash of a roles, either for
10888: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10889: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10890: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10891: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10892: For each key, value is set to colon-separated start and end times for
10893: the role. If no username and domain are specified, will default to
1.934 raeburn 10894: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10895: of role statuses (active, future or previous), roles
10896: (e.g., cc,in, st etc.) and domains of the roles which can be used
10897: to restrict the list of roles reported. If no array ref is
10898: provided for types, will default to return only active roles.
1.834 albertel 10899:
1.243 albertel 10900: =back
10901:
10902: =head2 User Modification
10903:
10904: =over 4
10905:
10906: =item *
10907:
1.957 raeburn 10908: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10909: user for the level given by URL. Optional start and end dates (leave empty
10910: string or zero for "no date")
1.191 harris41 10911:
10912: =item *
10913:
1.243 albertel 10914: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10915: change a users, password, possible return values are: ok,
10916: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10917: refused
1.191 harris41 10918:
10919: =item *
10920:
1.243 albertel 10921: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10922:
10923: =item *
10924:
1.1056.4.1 raeburn 10925: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10926: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10927:
10928: will update user information (firstname,middlename,lastname,generation,
10929: permanentemail), and if forceid is true, student/employee ID also.
10930: A user's institutional affiliation(s) can also be updated.
10931: User information fields will not be overwritten with empty entries
10932: unless the field is included in the $candelete array reference.
10933: This array is included when a single user is modified via "Manage Users",
10934: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10935:
10936: =item *
10937:
1.286 matthew 10938: modifystudent
10939:
1.957 raeburn 10940: modify a student's enrollment and identification information.
1.286 matthew 10941: The course id is resolved based on the current users environment.
10942: This means the envoking user must be a course coordinator or otherwise
10943: associated with a course.
10944:
1.297 matthew 10945: This call is essentially a wrapper for lonnet::modifyuser and
10946: lonnet::modify_student_enrollment
1.286 matthew 10947:
10948: Inputs:
10949:
10950: =over 4
10951:
1.957 raeburn 10952: =item B<$udom> Student's loncapa domain
1.286 matthew 10953:
1.957 raeburn 10954: =item B<$uname> Student's loncapa login name
1.286 matthew 10955:
1.964 bisitz 10956: =item B<$uid> Student/Employee ID
1.286 matthew 10957:
1.957 raeburn 10958: =item B<$umode> Student's authentication mode
1.286 matthew 10959:
1.957 raeburn 10960: =item B<$upass> Student's password
1.286 matthew 10961:
1.957 raeburn 10962: =item B<$first> Student's first name
1.286 matthew 10963:
1.957 raeburn 10964: =item B<$middle> Student's middle name
1.286 matthew 10965:
1.957 raeburn 10966: =item B<$last> Student's last name
1.286 matthew 10967:
1.957 raeburn 10968: =item B<$gene> Student's generation
1.286 matthew 10969:
1.957 raeburn 10970: =item B<$usec> Student's section in course
1.286 matthew 10971:
10972: =item B<$end> Unix time of the roles expiration
10973:
10974: =item B<$start> Unix time of the roles start date
10975:
10976: =item B<$forceid> If defined, allow $uid to be changed
10977:
10978: =item B<$desiredhome> server to use as home server for student
10979:
1.957 raeburn 10980: =item B<$email> Student's permanent e-mail address
10981:
10982: =item B<$type> Type of enrollment (auto or manual)
10983:
1.963 raeburn 10984: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10985:
10986: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10987:
1.963 raeburn 10988: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10989:
1.963 raeburn 10990: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10991:
1.963 raeburn 10992: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10993:
1.286 matthew 10994: =back
1.297 matthew 10995:
10996: =item *
10997:
10998: modify_student_enrollment
10999:
11000: Change a students enrollment status in a class. The environment variable
11001: 'role.request.course' must be defined for this function to proceed.
11002:
11003: Inputs:
11004:
11005: =over 4
11006:
11007: =item $udom, students domain
11008:
11009: =item $uname, students name
11010:
11011: =item $uid, students user id
11012:
11013: =item $first, students first name
11014:
11015: =item $middle
11016:
11017: =item $last
11018:
11019: =item $gene
11020:
11021: =item $usec
11022:
11023: =item $end
11024:
11025: =item $start
11026:
1.957 raeburn 11027: =item $type
11028:
11029: =item $locktype
11030:
11031: =item $cid
11032:
11033: =item $selfenroll
11034:
11035: =item $context
11036:
1.297 matthew 11037: =back
11038:
1.191 harris41 11039:
11040: =item *
11041:
1.243 albertel 11042: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11043: custom role; give a custom role to a user for the level given by URL. Specify
11044: name and domain of role author, and role name
1.191 harris41 11045:
11046: =item *
11047:
1.243 albertel 11048: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11049:
11050: =item *
11051:
1.243 albertel 11052: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11053:
11054: =back
11055:
11056: =head2 Course Infomation
11057:
11058: =over 4
1.191 harris41 11059:
11060: =item *
11061:
1.631 albertel 11062: coursedescription($courseid) : returns a hash of information about the
11063: specified course id, including all environment settings for the
11064: course, the description of the course will be in the hash under the
11065: key 'description'
1.191 harris41 11066:
11067: =item *
11068:
1.624 albertel 11069: resdata($name,$domain,$type,@which) : request for current parameter
11070: setting for a specific $type, where $type is either 'course' or 'user',
11071: @what should be a list of parameters to ask about. This routine caches
11072: answers for 5 minutes.
1.243 albertel 11073:
1.877 foxr 11074: =item *
11075:
11076: get_courseresdata($courseid, $domain) : dump the entire course resource
11077: data base, returning a hash that is keyed by the resource name and has
11078: values that are the resource value. I believe that the timestamps and
11079: versions are also returned.
11080:
11081:
1.243 albertel 11082: =back
11083:
11084: =head2 Course Modification
11085:
11086: =over 4
1.191 harris41 11087:
11088: =item *
11089:
1.243 albertel 11090: writecoursepref($courseid,%prefs) : write preferences (environment
11091: database) for a course
1.191 harris41 11092:
11093: =item *
11094:
1.1011 raeburn 11095: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11096:
11097: =item *
11098:
1.1038 raeburn 11099: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11100:
11101: =back
11102:
11103: =head2 Resource Subroutines
11104:
11105: =over 4
1.191 harris41 11106:
11107: =item *
11108:
1.243 albertel 11109: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11110:
11111: =item *
11112:
1.243 albertel 11113: repcopy($filename) : subscribes to the requested file, and attempts to
11114: replicate from the owning library server, Might return
1.607 raeburn 11115: 'unavailable', 'not_found', 'forbidden', 'ok', or
11116: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11117: resource. Expects the local filesystem pathname
11118: (/home/httpd/html/res/....)
11119:
11120: =back
11121:
11122: =head2 Resource Information
11123:
11124: =over 4
1.191 harris41 11125:
11126: =item *
11127:
1.243 albertel 11128: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11129: a vairety of different possible values, $varname should be a request
11130: string, and the other parameters can be used to specify who and what
11131: one is asking about.
11132:
11133: Possible values for $varname are environment.lastname (or other item
11134: from the envirnment hash), user.name (or someother aspect about the
11135: user), resource.0.maxtries (or some other part and parameter of a
11136: resource)
1.204 albertel 11137:
11138: =item *
11139:
1.243 albertel 11140: directcondval($number) : get current value of a condition; reads from a state
11141: string
1.204 albertel 11142:
11143: =item *
11144:
1.243 albertel 11145: condval($condidx) : value of condition index based on state
1.204 albertel 11146:
11147: =item *
11148:
1.243 albertel 11149: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11150: resource's metadata, $what should be either a specific key, or either
11151: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11152: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11153:
11154: this function automatically caches all requests
1.191 harris41 11155:
11156: =item *
11157:
1.243 albertel 11158: metadata_query($query,$custom,$customshow) : make a metadata query against the
11159: network of library servers; returns file handle of where SQL and regex results
11160: will be stored for query
1.191 harris41 11161:
11162: =item *
11163:
1.243 albertel 11164: symbread($filename) : return symbolic list entry (filename argument optional);
11165: returns the data handle
1.191 harris41 11166:
11167: =item *
11168:
1.243 albertel 11169: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11170: a possible symb for the URL in $thisfn, and if is an encryypted
11171: resource that the user accessed using /enc/ returns a 1 on success, 0
11172: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11173: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11174:
1.191 harris41 11175:
11176: =item *
11177:
1.243 albertel 11178: symbclean($symb) : removes versions numbers from a symb, returns the
11179: cleaned symb
1.191 harris41 11180:
11181: =item *
11182:
1.243 albertel 11183: is_on_map($uri) : checks if the $uri is somewhere on the current
11184: course map, user must be in a course for it to work.
1.191 harris41 11185:
11186: =item *
11187:
1.243 albertel 11188: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11189:
11190: =item *
11191:
1.243 albertel 11192: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11193: a random seed, all arguments are optional, if they aren't sent it uses the
11194: environment to derive them. Note: if symb isn't sent and it can't get one
11195: from &symbread it will use the current time as its return value
1.191 harris41 11196:
11197: =item *
11198:
1.243 albertel 11199: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11200: unfakeable, receipt
1.191 harris41 11201:
11202: =item *
11203:
1.620 albertel 11204: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11205:
11206: =item *
11207:
1.243 albertel 11208: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11209:
11210: =item *
11211:
1.243 albertel 11212: 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 11213:
11214: =item *
11215:
1.243 albertel 11216: 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 11217:
11218: =item *
11219:
1.243 albertel 11220: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11221:
11222: =item *
11223:
1.243 albertel 11224: devalidate($symb) : devalidate temporary spreadsheet calculations,
11225: forcing spreadsheet to reevaluate the resource scores next time.
11226:
11227: =back
11228:
11229: =head2 Storing/Retreiving Data
11230:
11231: =over 4
1.191 harris41 11232:
11233: =item *
11234:
1.243 albertel 11235: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11236: for this url; hashref needs to be given and should be a \%hashname; the
11237: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11238: be derived from the env
1.191 harris41 11239:
11240: =item *
11241:
1.243 albertel 11242: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11243: uses critical subroutine
1.191 harris41 11244:
11245: =item *
11246:
1.243 albertel 11247: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11248: all args are optional
1.191 harris41 11249:
11250: =item *
11251:
1.717 albertel 11252: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11253: dumps the complete (or key matching regexp) namespace into a hash
11254: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11255: normally &store()ed into
11256:
11257: $range should be either an integer '100' (give me the first 100
11258: matching records)
11259: or be two integers sperated by a - with no spaces
11260: '30-50' (give me the 30th through the 50th matching
11261: records)
11262:
11263:
11264: =item *
11265:
11266: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11267: replaces a &store() version of data with a replacement set of data
11268: for a particular resource in a namespace passed in the $storehash hash
11269: reference
11270:
11271: =item *
11272:
1.243 albertel 11273: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11274: works very similar to store/cstore, but all data is stored in a
11275: temporary location and can be reset using tmpreset, $storehash should
11276: be a hash reference, returns nothing on success
1.191 harris41 11277:
11278: =item *
11279:
1.243 albertel 11280: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11281: similar to restore, but all data is stored in a temporary location and
11282: can be reset using tmpreset. Returns a hash of values on success,
11283: error string otherwise.
1.191 harris41 11284:
11285: =item *
11286:
1.243 albertel 11287: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11288: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11289:
11290: =item *
11291:
1.243 albertel 11292: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11293: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11294:
11295: =item *
11296:
1.243 albertel 11297: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11298: namesp ($udom and $uname are optional)
1.191 harris41 11299:
11300: =item *
11301:
1.702 albertel 11302: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11303: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11304: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11305:
1.702 albertel 11306: $range should be either an integer '100' (give me the first 100
11307: matching records)
11308: or be two integers sperated by a - with no spaces
11309: '30-50' (give me the 30th through the 50th matching
11310: records)
1.449 matthew 11311: =item *
11312:
11313: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11314: $store can be a scalar, an array reference, or if the amount to be
11315: incremented is > 1, a hash reference.
11316:
11317: ($udom and $uname are optional)
1.191 harris41 11318:
11319: =item *
11320:
1.243 albertel 11321: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11322: ($udom and $uname are optional)
1.191 harris41 11323:
11324: =item *
11325:
1.243 albertel 11326: cput($namespace,$storehash,$udom,$uname) : critical put
11327: ($udom and $uname are optional)
1.191 harris41 11328:
11329: =item *
11330:
1.748 albertel 11331: newput($namespace,$storehash,$udom,$uname) :
11332:
11333: Attempts to store the items in the $storehash, but only if they don't
11334: currently exist, if this succeeds you can be certain that you have
11335: successfully created a new key value pair in the $namespace db.
11336:
11337:
11338: Args:
11339: $namespace: name of database to store values to
11340: $storehash: hashref to store to the db
11341: $udom: (optional) domain of user containing the db
11342: $uname: (optional) name of user caontaining the db
11343:
11344: Returns:
11345: 'ok' -> succeeded in storing all keys of $storehash
11346: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11347: least <key> already existed in the db (other
11348: requested keys may also already exist)
1.967 bisitz 11349: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11350: 'con_lost' -> unable to contact request server
11351: 'refused' -> action was not allowed by remote machine
11352:
11353:
11354: =item *
11355:
1.243 albertel 11356: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11357: reference filled in from namesp (encrypts the return communication)
11358: ($udom and $uname are optional)
1.191 harris41 11359:
11360: =item *
11361:
1.243 albertel 11362: log($udom,$name,$home,$message) : write to permanent log for user; use
11363: critical subroutine
11364:
1.806 raeburn 11365: =item *
11366:
1.860 raeburn 11367: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11368: array reference filled in from namespace found in domain level on either
11369: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11370:
11371: =item *
11372:
1.860 raeburn 11373: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11374: domain level either on specified domain server ($uhome) or primary domain
11375: server ($udom and $uhome are optional)
1.806 raeburn 11376:
1.943 raeburn 11377: =item *
11378:
11379: get_domain_defaults($target_domain) : returns hash with defaults for
11380: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11381: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11382: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11383: Values are retrieved from cache (if current), or from domain's configuration.db
11384: (if available), or lastly from values in lonTabs/dns_domain,tab,
11385: or lonTabs/domain.tab.
11386:
11387: %domdefaults = &get_auth_defaults($target_domain);
11388:
1.243 albertel 11389: =back
11390:
11391: =head2 Network Status Functions
11392:
11393: =over 4
1.191 harris41 11394:
11395: =item *
11396:
11397: dirlist($uri) : return directory list based on URI
11398:
11399: =item *
11400:
1.243 albertel 11401: spareserver() : find server with least workload from spare.tab
11402:
1.986 foxr 11403:
11404: =item *
11405:
11406: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11407: if there is no corresponding loncapa host.
11408:
1.243 albertel 11409: =back
11410:
1.986 foxr 11411:
1.243 albertel 11412: =head2 Apache Request
11413:
11414: =over 4
1.191 harris41 11415:
11416: =item *
11417:
1.243 albertel 11418: ssi($url,%hash) : server side include, does a complete request cycle on url to
11419: localhost, posts hash
11420:
11421: =back
11422:
11423: =head2 Data to String to Data
11424:
11425: =over 4
1.191 harris41 11426:
11427: =item *
11428:
1.243 albertel 11429: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11430: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11431:
11432: =item *
11433:
1.243 albertel 11434: hashref2str($hashref) : convert a hashref into a string complete with
11435: escaping and '=' and '&' separators, supports elements that are
11436: arrayrefs and hashrefs
1.191 harris41 11437:
11438: =item *
11439:
1.243 albertel 11440: arrayref2str($arrayref) : convert an arrayref into a string complete
11441: with escaping and '&' separators, supports elements that are arrayrefs
11442: and hashrefs
1.191 harris41 11443:
11444: =item *
11445:
1.243 albertel 11446: str2hash($string) : convert string to hash using unescaping and
11447: splitting on '=' and '&', supports elements that are arrayrefs and
11448: hashrefs
1.191 harris41 11449:
11450: =item *
11451:
1.243 albertel 11452: str2array($string) : convert string to hash using unescaping and
11453: splitting on '&', supports elements that are arrayrefs and hashrefs
11454:
11455: =back
11456:
11457: =head2 Logging Routines
11458:
11459: These routines allow one to make log messages in the lonnet.log and
11460: lonnet.perm logfiles.
1.191 harris41 11461:
1.1056.4.31 raeburn 11462: =over 4
11463:
1.191 harris41 11464: =item *
11465:
1.243 albertel 11466: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11467:
11468: =item *
11469:
1.243 albertel 11470: logthis() : append message to the normal lonnet.log file, it gets
11471: preiodically rolled over and deleted.
1.191 harris41 11472:
11473: =item *
11474:
1.243 albertel 11475: logperm() : append a permanent message to lonnet.perm.log, this log
11476: file never gets deleted by any automated portion of the system, only
11477: messages of critical importance should go in here.
11478:
11479: =back
11480:
11481: =head2 General File Helper Routines
11482:
11483: =over 4
1.191 harris41 11484:
11485: =item *
11486:
1.481 raeburn 11487: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11488: (a) files in /uploaded
11489: (i) If a local copy of the file exists -
11490: compares modification date of local copy with last-modified date for
11491: definitive version stored on home server for course. If local copy is
11492: stale, requests a new version from the home server and stores it.
11493: If the original has been removed from the home server, then local copy
11494: is unlinked.
11495: (ii) If local copy does not exist -
11496: requests the file from the home server and stores it.
11497:
11498: If $caller is 'uploadrep':
11499: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11500: for request for files originally uploaded via DOCS.
11501: - returns 'ok' if fresh local copy now available, -1 otherwise.
11502:
11503: Otherwise:
11504: This indicates a call from the content generation phase of the request.
11505: - returns the entire contents of the file or -1.
11506:
11507: (b) files in /res
11508: - returns the entire contents of a file or -1;
11509: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11510:
1.712 albertel 11511:
11512: =item *
11513:
11514: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11515: reference
11516:
11517: returns either a stat() list of data about the file or an empty list
11518: if the file doesn't exist or couldn't find out about it (connection
11519: problems or user unknown)
11520:
1.191 harris41 11521: =item *
11522:
1.243 albertel 11523: filelocation($dir,$file) : returns file system location of a file
11524: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11525: directory that relative $file lookups are to looked in ($dir of /a/dir
11526: and a file of ../bob will become /a/bob)
1.191 harris41 11527:
11528: =item *
11529:
11530: hreflocation($dir,$file) : returns file system location or a URL; same as
11531: filelocation except for hrefs
11532:
11533: =item *
11534:
11535: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11536:
1.243 albertel 11537: =back
11538:
1.608 albertel 11539: =head2 Usererfile file routines (/uploaded*)
11540:
11541: =over 4
11542:
11543: =item *
11544:
11545: userfileupload(): main rotine for putting a file in a user or course's
11546: filespace, arguments are,
11547:
1.620 albertel 11548: formname - required - this is the name of the element in $env where the
1.608 albertel 11549: filename, and the contents of the file to create/modifed exist
1.620 albertel 11550: the filename is in $env{'form.'.$formname.'.filename'} and the
11551: contents of the file is located in $env{'form.'.$formname}
1.1056.4.13 raeburn 11552: context - if coursedoc, store the file in the course of the active role
11553: of the current user;
11554: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11555: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11556: subdir - required - subdirectory to put the file in under ../userfiles/
11557: if undefined, it will be placed in "unknown"
11558:
11559: (This routine calls clean_filename() to remove any dangerous
11560: characters from the filename, and then calls finuserfileupload() to
11561: complete the transaction)
11562:
11563: returns either the url of the uploaded file (/uploaded/....) if successful
11564: and /adm/notfound.html if unsuccessful
11565:
11566: =item *
11567:
11568: clean_filename(): routine for cleaing a filename up for storage in
11569: userfile space, argument is:
11570:
11571: filename - proposed filename
11572:
11573: returns: the new clean filename
11574:
11575: =item *
11576:
1.1056.4.13 raeburn 11577: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11578: userspace, probably shouldn't be called directly
11579:
11580: docuname: username or courseid of destination for the file
11581: docudom: domain of user/course of destination for the file
11582: formname: same as for userfileupload()
1.1056.4.13 raeburn 11583: fname: filename (including subdirectories) for the file
11584: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11585: allfiles: reference to hash used to store objects found by parser
11586: codebase: reference to hash used for codebases of java objects found by parser
11587: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11588: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11589: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11590: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11591: context: if 'overwrite', will move the uploaded file from its temporary location to
11592: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16 raeburn 11593: mimetype: reference to scalar to accommodate mime type determined
11594: from File::MMagic if $parser = parse.
1.608 albertel 11595:
11596: returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13 raeburn 11597: and /adm/notfound.html if unsuccessful (or an error message if context
11598: was 'overwrite').
11599:
1.608 albertel 11600:
11601: =item *
11602:
11603: renameuserfile(): renames an existing userfile to a new name
11604:
11605: Args:
11606: docuname: username or courseid of destination for the file
11607: docudom: domain of user/course of destination for the file
11608: old: current file name (including any subdirs under userfiles)
11609: new: desired file name (including any subdirs under userfiles)
11610:
11611: =item *
11612:
11613: mkdiruserfile(): creates a directory is a userfiles dir
11614:
11615: Args:
11616: docuname: username or courseid of destination for the file
11617: docudom: domain of user/course of destination for the file
11618: dir: dir to create (including any subdirs under userfiles)
11619:
11620: =item *
11621:
11622: removeuserfile(): removes a file that exists in userfiles
11623:
11624: Args:
11625: docuname: username or courseid of destination for the file
11626: docudom: domain of user/course of destination for the file
11627: fname: filname to delete (including any subdirs under userfiles)
11628:
11629: =item *
11630:
11631: removeuploadedurl(): convience function for removeuserfile()
11632:
11633: Args:
11634: url: a full /uploaded/... url to delete
11635:
1.747 albertel 11636: =item *
11637:
11638: get_portfile_permissions():
11639: Args:
11640: domain: domain of user or course contain the portfolio files
11641: user: name of user or num of course contain the portfolio files
11642: Returns:
11643: hashref of a dump of the proper file_permissions.db
11644:
11645:
11646: =item *
11647:
11648: get_access_controls():
11649:
11650: Args:
11651: current_permissions: the hash ref returned from get_portfile_permissions()
11652: group: (optional) the group you want the files associated with
11653: file: (optional) the file you want access info on
11654:
11655: Returns:
1.749 raeburn 11656: a hash (keys are file names) of hashes containing
11657: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11658: values are XML containing access control settings (see below)
1.747 albertel 11659:
11660: Internal notes:
11661:
1.749 raeburn 11662: access controls are stored in file_permissions.db as key=value pairs.
11663: key -> path to file/file_name\0uniqueID:scope_end_start
11664: where scope -> public,guest,course,group,domains or users.
11665: end -> UNIX time for end of access (0 -> no end date)
11666: start -> UNIX time for start of access
11667:
11668: value -> XML description of access control
11669: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11670: <start></start>
11671: <end></end>
11672:
11673: <password></password> for scope type = guest
11674:
11675: <domain></domain> for scope type = course or group
11676: <number></number>
11677: <roles id="">
11678: <role></role>
11679: <access></access>
11680: <section></section>
11681: <group></group>
11682: </roles>
11683:
11684: <dom></dom> for scope type = domains
11685:
11686: <users> for scope type = users
11687: <user>
11688: <uname></uname>
11689: <udom></udom>
11690: </user>
11691: </users>
11692: </scope>
11693:
11694: Access data is also aggregated for each file in an additional key=value pair:
11695: key -> path to file/file_name\0accesscontrol
11696: value -> reference to hash
11697: hash contains key = value pairs
11698: where key = uniqueID:scope_end_start
11699: value = UNIX time record was last updated
11700:
11701: Used to improve speed of look-ups of access controls for each file.
11702:
11703: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11704:
11705: modify_access_controls():
11706:
11707: Modifies access controls for a portfolio file
11708: Args
11709: 1. file name
11710: 2. reference to hash of required changes,
11711: 3. domain
11712: 4. username
11713: where domain,username are the domain of the portfolio owner
11714: (either a user or a course)
11715:
11716: Returns:
11717: 1. result of additions or updates ('ok' or 'error', with error message).
11718: 2. result of deletions ('ok' or 'error', with error message).
11719: 3. reference to hash of any new or updated access controls.
11720: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11721: key = integer (inbound ID)
11722: value = uniqueID
1.747 albertel 11723:
1.608 albertel 11724: =back
11725:
1.243 albertel 11726: =head2 HTTP Helper Routines
11727:
11728: =over 4
11729:
1.191 harris41 11730: =item *
11731:
11732: escape() : unpack non-word characters into CGI-compatible hex codes
11733:
11734: =item *
11735:
11736: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11737:
1.243 albertel 11738: =back
11739:
11740: =head1 PRIVATE SUBROUTINES
11741:
11742: =head2 Underlying communication routines (Shouldn't call)
11743:
11744: =over 4
11745:
11746: =item *
11747:
11748: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11749:
11750: =item *
11751:
11752: reply() : uses subreply to send a message to remote machine, logs all failures
11753:
11754: =item *
11755:
11756: critical() : passes a critical message to another server; if cannot
11757: get through then place message in connection buffer directory and
11758: returns con_delayed, if incapable of saving message, returns
11759: con_failed
11760:
11761: =item *
11762:
11763: reconlonc() : tries to reconnect lonc client processes.
11764:
11765: =back
11766:
11767: =head2 Resource Access Logging
11768:
11769: =over 4
11770:
11771: =item *
11772:
11773: flushcourselogs() : flush (save) buffer logs and access logs
11774:
11775: =item *
11776:
11777: courselog($what) : save message for course in hash
11778:
11779: =item *
11780:
11781: courseacclog($what) : save message for course using &courselog(). Perform
11782: special processing for specific resource types (problems, exams, quizzes, etc).
11783:
1.191 harris41 11784: =item *
11785:
11786: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11787: as a PerlChildExitHandler
1.243 albertel 11788:
11789: =back
11790:
11791: =head2 Other
11792:
11793: =over 4
11794:
11795: =item *
11796:
11797: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11798:
11799: =back
11800:
11801: =cut
1.877 foxr 11802:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>