Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.2.8
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.2.8! raeburn 4: # $Id: lonnet.pm,v 1.1056.2.7 2010/10/01 14:26:24 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.968 raeburn 79: $_64bit %env %protocol);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
199: my ($dom,$lonhost) = @_;
200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
214: my $cachetime = 24*3600;
215: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
216: if (defined($cached)) {
217: return $loncaparev;
218: } else {
219: my $loncaparev = &reply('serverloncaparev',$lonhost);
220: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
221: }
222: }
223: }
224:
1.1 albertel 225: # -------------------------------------------------- Non-critical communication
226: sub subreply {
227: my ($cmd,$server)=@_;
1.838 albertel 228: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 229: #
230: # With loncnew process trimming, there's a timing hole between lonc server
231: # process exit and the master server picking up the listen on the AF_UNIX
232: # socket. In that time interval, a lock file will exist:
233:
234: my $lockfile=$peerfile.".lock";
235: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
236: sleep(1);
237: }
238: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 239: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 240: #
1.550 foxr 241: # We'll give the connection a few tries before abandoning it. If
242: # connection is not possible, we'll con_lost back to the client.
243: #
244: my $client;
245: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
246: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
247: Type => SOCK_STREAM,
248: Timeout => 10);
1.869 albertel 249: if ($client) {
1.550 foxr 250: last; # Connected!
1.850 albertel 251: } else {
1.853 albertel 252: &create_connection(&hostname($server),$server);
1.550 foxr 253: }
1.850 albertel 254: sleep(1); # Try again later if failed connection.
1.550 foxr 255: }
256: my $answer;
257: if ($client) {
1.704 albertel 258: print $client "sethost:$server:$cmd\n";
1.550 foxr 259: $answer=<$client>;
260: if (!$answer) { $answer="con_lost"; }
261: chomp($answer);
262: } else {
263: $answer = 'con_lost'; # Failed connection.
264: }
1.1 albertel 265: return $answer;
266: }
267:
268: sub reply {
269: my ($cmd,$server)=@_;
1.838 albertel 270: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 271: my $answer=subreply($cmd,$server);
1.65 www 272: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 273: &logthis("<font color=\"blue\">WARNING:".
1.12 www 274: " $cmd to $server returned $answer</font>");
275: }
1.1 albertel 276: return $answer;
277: }
278:
279: # ----------------------------------------------------------- Send USR1 to lonc
280:
281: sub reconlonc {
1.891 albertel 282: my ($lonid) = @_;
283: my $hostname = &hostname($lonid);
284: if ($lonid) {
285: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
286: if ($hostname && -e $peerfile) {
287: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
288: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
289: Type => SOCK_STREAM,
290: Timeout => 10);
291: if ($client) {
292: print $client ("reset_retries\n");
293: my $answer=<$client>;
294: #reset just this one.
295: }
296: }
297: return;
298: }
299:
1.836 www 300: &logthis("Trying to reconnect lonc");
1.1 albertel 301: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 302: if (open(my $fh,"<$loncfile")) {
1.1 albertel 303: my $loncpid=<$fh>;
304: chomp($loncpid);
305: if (kill 0 => $loncpid) {
306: &logthis("lonc at pid $loncpid responding, sending USR1");
307: kill USR1 => $loncpid;
308: sleep 1;
1.836 www 309: } else {
1.12 www 310: &logthis(
1.672 albertel 311: "<font color=\"blue\">WARNING:".
1.12 www 312: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 313: }
314: } else {
1.836 www 315: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 316: }
317: }
318:
319: # ------------------------------------------------------ Critical communication
1.12 www 320:
1.1 albertel 321: sub critical {
322: my ($cmd,$server)=@_;
1.838 albertel 323: unless (&hostname($server)) {
1.672 albertel 324: &logthis("<font color=\"blue\">WARNING:".
1.89 www 325: " Critical message to unknown server ($server)</font>");
326: return 'no_such_host';
327: }
1.1 albertel 328: my $answer=reply($cmd,$server);
329: if ($answer eq 'con_lost') {
330: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 331: my $answer=reply($cmd,$server);
1.1 albertel 332: if ($answer eq 'con_lost') {
333: my $now=time;
334: my $middlename=$cmd;
1.5 www 335: $middlename=substr($middlename,0,16);
1.1 albertel 336: $middlename=~s/\W//g;
337: my $dfilename=
1.305 www 338: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
339: $dumpcount++;
1.1 albertel 340: {
1.448 albertel 341: my $dfh;
342: if (open($dfh,">$dfilename")) {
343: print $dfh "$cmd\n";
344: close($dfh);
345: }
1.1 albertel 346: }
347: sleep 2;
348: my $wcmd='';
349: {
1.448 albertel 350: my $dfh;
351: if (open($dfh,"<$dfilename")) {
352: $wcmd=<$dfh>;
353: close($dfh);
354: }
1.1 albertel 355: }
356: chomp($wcmd);
1.7 www 357: if ($wcmd eq $cmd) {
1.672 albertel 358: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 359: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 360: &logperm("D:$server:$cmd");
361: return 'con_delayed';
362: } else {
1.672 albertel 363: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 364: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 365: &logperm("F:$server:$cmd");
366: return 'con_failed';
367: }
368: }
369: }
370: return $answer;
1.405 albertel 371: }
372:
1.755 albertel 373: # ------------------------------------------- check if return value is an error
374:
375: sub error {
376: my ($result) = @_;
1.756 albertel 377: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 378: if ($2 == 2) { return undef; }
379: return $1;
380: }
381: return undef;
382: }
383:
1.783 albertel 384: sub convert_and_load_session_env {
385: my ($lonidsdir,$handle)=@_;
386: my @profile;
387: {
1.917 albertel 388: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
389: if (!$opened) {
1.915 albertel 390: return 0;
391: }
1.783 albertel 392: flock($idf,LOCK_SH);
393: @profile=<$idf>;
394: close($idf);
395: }
396: my %temp_env;
397: foreach my $line (@profile) {
1.786 albertel 398: if ($line !~ m/=/) {
399: return 0;
400: }
1.783 albertel 401: chomp($line);
402: my ($envname,$envvalue)=split(/=/,$line,2);
403: $temp_env{&unescape($envname)} = &unescape($envvalue);
404: }
405: unlink("$lonidsdir/$handle.id");
406: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
407: 0640)) {
408: %disk_env = %temp_env;
409: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
410: untie(%disk_env);
411: }
1.786 albertel 412: return 1;
1.783 albertel 413: }
414:
1.374 www 415: # ------------------------------------------- Transfer profile into environment
1.780 albertel 416: my $env_loaded;
417: sub transfer_profile_to_env {
1.788 albertel 418: my ($lonidsdir,$handle,$force_transfer) = @_;
419: if (!$force_transfer && $env_loaded) { return; }
1.374 www 420:
1.720 albertel 421: if (!defined($lonidsdir)) {
422: $lonidsdir = $perlvar{'lonIDsDir'};
423: }
424: if (!defined($handle)) {
425: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
426: }
427:
1.786 albertel 428: my $convert;
429: {
1.917 albertel 430: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
431: if (!$opened) {
1.915 albertel 432: return;
433: }
1.786 albertel 434: flock($idf,LOCK_SH);
435: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
436: &GDBM_READER(),0640)) {
437: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
438: untie(%disk_env);
439: } else {
440: $convert = 1;
441: }
442: }
443: if ($convert) {
444: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
445: &logthis("Failed to load session, or convert session.");
446: }
1.374 www 447: }
1.783 albertel 448:
1.786 albertel 449: my %remove;
1.783 albertel 450: while ( my $envname = each(%env) ) {
1.433 matthew 451: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
452: if ($time < time-300) {
1.783 albertel 453: $remove{$key}++;
1.433 matthew 454: }
455: }
456: }
1.783 albertel 457:
1.619 albertel 458: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 459: $env_loaded=1;
1.783 albertel 460: foreach my $expired_key (keys(%remove)) {
1.433 matthew 461: &delenv($expired_key);
1.374 www 462: }
1.1 albertel 463: }
464:
1.916 albertel 465: # ---------------------------------------------------- Check for valid session
466: sub check_for_valid_session {
467: my ($r) = @_;
468: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
469: my $lonid=$cookies{'lonID'};
470: return undef if (!$lonid);
471:
472: my $handle=&LONCAPA::clean_handle($lonid->value);
473: my $lonidsdir=$r->dir_config('lonIDsDir');
474: return undef if (!-e "$lonidsdir/$handle.id");
475:
1.917 albertel 476: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
477: return undef if (!$opened);
1.916 albertel 478:
479: flock($idf,LOCK_SH);
480: my %disk_env;
481: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
482: &GDBM_READER(),0640)) {
483: return undef;
484: }
485:
486: if (!defined($disk_env{'user.name'})
487: || !defined($disk_env{'user.domain'})) {
488: return undef;
489: }
490: return $handle;
491: }
492:
1.830 albertel 493: sub timed_flock {
494: my ($file,$lock_type) = @_;
495: my $failed=0;
496: eval {
497: local $SIG{__DIE__}='DEFAULT';
498: local $SIG{ALRM}=sub {
499: $failed=1;
500: die("failed lock");
501: };
502: alarm(13);
503: flock($file,$lock_type);
504: alarm(0);
505: };
506: if ($failed) {
507: return undef;
508: } else {
509: return 1;
510: }
511: }
512:
1.5 www 513: # ---------------------------------------------------------- Append Environment
514:
515: sub appenv {
1.949 raeburn 516: my ($newenv,$roles) = @_;
517: if (ref($newenv) eq 'HASH') {
518: foreach my $key (keys(%{$newenv})) {
519: my $refused = 0;
520: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
521: $refused = 1;
522: if (ref($roles) eq 'ARRAY') {
523: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
524: if (grep(/^\Q$role\E$/,@{$roles})) {
525: $refused = 0;
526: }
527: }
528: }
529: if ($refused) {
530: &logthis("<font color=\"blue\">WARNING: ".
531: "Attempt to modify environment ".$key." to ".$newenv->{$key}
532: .'</font>');
533: delete($newenv->{$key});
534: } else {
535: $env{$key}=$newenv->{$key};
536: }
537: }
538: my $opened = open(my $env_file,'+<',$env{'user.environment'});
539: if ($opened
540: && &timed_flock($env_file,LOCK_EX)
541: &&
542: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
543: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
544: while (my ($key,$value) = each(%{$newenv})) {
545: $disk_env{$key} = $value;
546: }
547: untie(%disk_env);
1.35 www 548: }
1.191 harris41 549: }
1.56 www 550: return 'ok';
551: }
552: # ----------------------------------------------------- Delete from Environment
553:
554: sub delenv {
1.987 raeburn 555: my ($delthis,$regexp) = @_;
1.56 www 556: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 557: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 558: "Attempt to delete from environment ".$delthis);
559: return 'error';
560: }
1.917 albertel 561: my $opened = open(my $env_file,'+<',$env{'user.environment'});
562: if ($opened
1.915 albertel 563: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 564: &&
565: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
566: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 567: foreach my $key (keys(%disk_env)) {
1.987 raeburn 568: if ($regexp) {
569: if ($key=~/^$delthis/) {
570: delete($env{$key});
571: delete($disk_env{$key});
572: }
573: } else {
574: if ($key=~/^\Q$delthis\E/) {
575: delete($env{$key});
576: delete($disk_env{$key});
577: }
578: }
1.448 albertel 579: }
1.783 albertel 580: untie(%disk_env);
1.5 www 581: }
582: return 'ok';
1.369 albertel 583: }
584:
1.790 albertel 585: sub get_env_multiple {
586: my ($name) = @_;
587: my @values;
588: if (defined($env{$name})) {
589: # exists is it an array
590: if (ref($env{$name})) {
591: @values=@{ $env{$name} };
592: } else {
593: $values[0]=$env{$name};
594: }
595: }
596: return(@values);
597: }
598:
1.958 www 599: # ------------------------------------------------------------------- Locking
600:
601: sub set_lock {
602: my ($text)=@_;
603: $locknum++;
604: my $id=$$.'-'.$locknum;
605: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
606: 'session.lock.'.$id => $text});
607: return $id;
608: }
609:
610: sub get_locks {
611: my $num=0;
612: my %texts=();
613: foreach my $lock (split(/\,/,$env{'session.locks'})) {
614: if ($lock=~/\w/) {
615: $num++;
616: $texts{$lock}=$env{'session.lock.'.$lock};
617: }
618: }
619: return ($num,%texts);
620: }
621:
622: sub remove_lock {
623: my ($id)=@_;
624: my $newlocks='';
625: foreach my $lock (split(/\,/,$env{'session.locks'})) {
626: if (($lock=~/\w/) && ($lock ne $id)) {
627: $newlocks.=','.$lock;
628: }
629: }
630: &appenv({'session.locks' => $newlocks});
631: &delenv('session.lock.'.$id);
632: }
633:
634: sub remove_all_locks {
635: my $activelocks=$env{'session.locks'};
636: foreach my $lock (split(/\,/,$env{'session.locks'})) {
637: if ($lock=~/\w/) {
638: &remove_lock($lock);
639: }
640: }
641: }
642:
643:
1.369 albertel 644: # ------------------------------------------ Find out current server userload
645: sub userload {
646: my $numusers=0;
647: {
648: opendir(LONIDS,$perlvar{'lonIDsDir'});
649: my $filename;
650: my $curtime=time;
651: while ($filename=readdir(LONIDS)) {
1.925 albertel 652: next if ($filename eq '.' || $filename eq '..');
653: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 654: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 655: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 656: }
657: closedir(LONIDS);
658: }
659: my $userloadpercent=0;
660: my $maxuserload=$perlvar{'lonUserLoadLim'};
661: if ($maxuserload) {
1.371 albertel 662: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 663: }
1.372 albertel 664: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 665: return $userloadpercent;
1.283 www 666: }
667:
668: # ------------------------------------------ Fight off request when overloaded
669:
670: sub overloaderror {
671: my ($r,$checkserver)=@_;
672: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
673: my $loadavg;
674: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 675: open(my $loadfile,'/proc/loadavg');
1.283 www 676: $loadavg=<$loadfile>;
677: $loadavg =~ s/\s.*//g;
1.285 matthew 678: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 679: close($loadfile);
1.283 www 680: } else {
681: $loadavg=&reply('load',$checkserver);
682: }
1.285 matthew 683: my $overload=$loadavg-100;
1.283 www 684: if ($overload>0) {
1.285 matthew 685: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 686: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 687: return 413;
1.283 www 688: }
689: return '';
1.5 www 690: }
1.1 albertel 691:
692: # ------------------------------ Find server with least workload from spare.tab
1.11 www 693:
1.1 albertel 694: sub spareserver {
1.670 albertel 695: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 696: my $spare_server;
1.370 albertel 697: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 698: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
699: : $userloadpercent;
700:
701: foreach my $try_server (@{ $spareid{'primary'} }) {
702: ($spare_server, $lowest_load) =
703: &compare_server_load($try_server, $spare_server, $lowest_load);
704: }
705:
706: my $found_server = ($spare_server ne '' && $lowest_load < 100);
707:
708: if (!$found_server) {
709: foreach my $try_server (@{ $spareid{'default'} }) {
710: ($spare_server, $lowest_load) =
711: &compare_server_load($try_server, $spare_server, $lowest_load);
712: }
713: }
714:
715: if (!$want_server_name) {
1.968 raeburn 716: my $protocol = 'http';
717: if ($protocol{$spare_server} eq 'https') {
718: $protocol = $protocol{$spare_server};
719: }
1.1001 raeburn 720: if (defined($spare_server)) {
721: my $hostname = &hostname($spare_server);
722: if (defined($hostname)) {
723: $spare_server = $protocol.'://'.$hostname;
724: }
725: }
1.784 albertel 726: }
727: return $spare_server;
728: }
729:
730: sub compare_server_load {
731: my ($try_server, $spare_server, $lowest_load) = @_;
732:
733: my $loadans = &reply('load', $try_server);
734: my $userloadans = &reply('userload',$try_server);
735:
736: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
737: next; #didn't get a number from the server
738: }
739:
740: my $load;
741: if ($loadans =~ /\d/) {
742: if ($userloadans =~ /\d/) {
743: #both are numbers, pick the bigger one
744: $load = ($loadans > $userloadans) ? $loadans
745: : $userloadans;
1.411 albertel 746: } else {
1.784 albertel 747: $load = $loadans;
1.411 albertel 748: }
1.784 albertel 749: } else {
750: $load = $userloadans;
751: }
752:
753: if (($load =~ /\d/) && ($load < $lowest_load)) {
754: $spare_server = $try_server;
755: $lowest_load = $load;
1.370 albertel 756: }
1.784 albertel 757: return ($spare_server,$lowest_load);
1.202 matthew 758: }
1.914 albertel 759:
760: # --------------------------- ask offload servers if user already has a session
761: sub find_existing_session {
762: my ($udom,$uname) = @_;
763: foreach my $try_server (@{ $spareid{'primary'} },
764: @{ $spareid{'default'} }) {
765: return $try_server if (&has_user_session($try_server, $udom, $uname));
766: }
767: return;
768: }
769:
770: # -------------------------------- ask if server already has a session for user
771: sub has_user_session {
772: my ($lonid,$udom,$uname) = @_;
773: my $result = &reply(join(':','userhassession',
774: map {&escape($_)} ($udom,$uname)),$lonid);
775: return 1 if ($result eq 'ok');
776:
777: return 0;
778: }
779:
1.202 matthew 780: # --------------------------------------------- Try to change a user's password
781:
782: sub changepass {
1.799 raeburn 783: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 784: $currentpass = &escape($currentpass);
785: $newpass = &escape($newpass);
1.1030 raeburn 786: my $lonhost = $perlvar{'lonHostID'};
787: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 788: $server);
789: if (! $answer) {
790: &logthis("No reply on password change request to $server ".
791: "by $uname in domain $udom.");
792: } elsif ($answer =~ "^ok") {
793: &logthis("$uname in $udom successfully changed their password ".
794: "on $server.");
795: } elsif ($answer =~ "^pwchange_failure") {
796: &logthis("$uname in $udom was unable to change their password ".
797: "on $server. The action was blocked by either lcpasswd ".
798: "or pwchange");
799: } elsif ($answer =~ "^non_authorized") {
800: &logthis("$uname in $udom did not get their password correct when ".
801: "attempting to change it on $server.");
802: } elsif ($answer =~ "^auth_mode_error") {
803: &logthis("$uname in $udom attempted to change their password despite ".
804: "not being locally or internally authenticated on $server.");
805: } elsif ($answer =~ "^unknown_user") {
806: &logthis("$uname in $udom attempted to change their password ".
807: "on $server but were unable to because $server is not ".
808: "their home server.");
809: } elsif ($answer =~ "^refused") {
810: &logthis("$server refused to change $uname in $udom password because ".
811: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 812: } elsif ($answer =~ "invalid_client") {
813: &logthis("$server refused to change $uname in $udom password because ".
814: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 815: }
816: return $answer;
1.1 albertel 817: }
818:
1.169 harris41 819: # ----------------------- Try to determine user's current authentication scheme
820:
821: sub queryauthenticate {
822: my ($uname,$udom)=@_;
1.456 albertel 823: my $uhome=&homeserver($uname,$udom);
824: if (!$uhome) {
825: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
826: return 'no_host';
827: }
828: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
829: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
830: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 831: }
1.456 albertel 832: return $answer;
1.169 harris41 833: }
834:
1.1 albertel 835: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 836:
1.1 albertel 837: sub authenticate {
1.952 raeburn 838: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 839: $upass=&escape($upass);
840: $uname= &LONCAPA::clean_username($uname);
1.836 www 841: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 842: my $newhome;
1.836 www 843: if ((!$uhome) || ($uhome eq 'no_host')) {
844: # Maybe the machine was offline and only re-appeared again recently?
845: &reconlonc();
846: # One more
1.952 raeburn 847: $uhome=&homeserver($uname,$udom,1);
848: if (($uhome eq 'no_host') && $checkdefauth) {
849: if (defined(&domain($udom,'primary'))) {
850: $newhome=&domain($udom,'primary');
851: }
852: if ($newhome ne '') {
853: $uhome = $newhome;
854: }
855: }
1.836 www 856: if ((!$uhome) || ($uhome eq 'no_host')) {
857: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 858: return 'no_host';
859: }
1.1 albertel 860: }
1.952 raeburn 861: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 862: if ($answer eq 'authorized') {
1.952 raeburn 863: if ($newhome) {
864: &logthis("User $uname at $udom authorized by $uhome, but needs account");
865: return 'no_account_on_host';
866: } else {
867: &logthis("User $uname at $udom authorized by $uhome");
868: return $uhome;
869: }
1.471 albertel 870: }
871: if ($answer eq 'non_authorized') {
872: &logthis("User $uname at $udom rejected by $uhome");
873: return 'no_host';
1.9 www 874: }
1.471 albertel 875: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 876: return 'no_host';
877: }
878:
879: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 880:
1.599 albertel 881: my %homecache;
1.1 albertel 882: sub homeserver {
1.230 stredwic 883: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 884: my $index="$uname:$udom";
1.426 albertel 885:
1.599 albertel 886: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 887:
888: my %servers = &get_servers($udom,'library');
889: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 890: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 891: exists($badServerCache{$tryserver}));
1.841 albertel 892:
893: my $answer=reply("home:$udom:$uname",$tryserver);
894: if ($answer eq 'found') {
895: delete($badServerCache{$tryserver});
896: return $homecache{$index}=$tryserver;
897: } elsif ($answer eq 'no_host') {
898: $badServerCache{$tryserver}=1;
899: }
1.1 albertel 900: }
901: return 'no_host';
1.70 www 902: }
903:
904: # ------------------------------------- Find the usernames behind a list of IDs
905:
906: sub idget {
907: my ($udom,@ids)=@_;
908: my %returnhash=();
909:
1.841 albertel 910: my %servers = &get_servers($udom,'library');
911: foreach my $tryserver (keys(%servers)) {
912: my $idlist=join('&',@ids);
913: $idlist=~tr/A-Z/a-z/;
914: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
915: my @answer=();
916: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
917: @answer=split(/\&/,$reply);
918: } ;
919: my $i;
920: for ($i=0;$i<=$#ids;$i++) {
921: if ($answer[$i]) {
922: $returnhash{$ids[$i]}=$answer[$i];
923: }
924: }
925: }
1.70 www 926: return %returnhash;
927: }
928:
929: # ------------------------------------- Find the IDs behind a list of usernames
930:
931: sub idrget {
932: my ($udom,@unames)=@_;
933: my %returnhash=();
1.800 albertel 934: foreach my $uname (@unames) {
935: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 936: }
1.70 www 937: return %returnhash;
938: }
939:
940: # ------------------------------- Store away a list of names and associated IDs
941:
942: sub idput {
943: my ($udom,%ids)=@_;
944: my %servers=();
1.800 albertel 945: foreach my $uname (keys(%ids)) {
946: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
947: my $uhom=&homeserver($uname,$udom);
1.70 www 948: if ($uhom ne 'no_host') {
1.800 albertel 949: my $id=&escape($ids{$uname});
1.70 www 950: $id=~tr/A-Z/a-z/;
1.800 albertel 951: my $esc_unam=&escape($uname);
1.70 www 952: if ($servers{$uhom}) {
1.800 albertel 953: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 954: } else {
1.800 albertel 955: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 956: }
957: }
1.191 harris41 958: }
1.800 albertel 959: foreach my $server (keys(%servers)) {
960: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 961: }
1.344 www 962: }
963:
1.1023 raeburn 964: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 965: sub dump_dom {
1.1023 raeburn 966: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 967: if (!$udom) {
968: $udom=$env{'user.domain'};
969: }
970: my %returnhash;
1.1023 raeburn 971: if ($udom) {
972: my $uname = &get_domainconfiguser($udom);
973: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 974: }
975: return %returnhash;
976: }
977:
1.1023 raeburn 978: # ------------------------------------------ get items from domain db files
1.806 raeburn 979:
980: sub get_dom {
1.860 raeburn 981: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 982: my $items='';
983: foreach my $item (@$storearr) {
984: $items.=&escape($item).'&';
985: }
986: $items=~s/\&$//;
1.860 raeburn 987: if (!$udom) {
988: $udom=$env{'user.domain'};
989: if (defined(&domain($udom,'primary'))) {
990: $uhome=&domain($udom,'primary');
991: } else {
1.874 albertel 992: undef($uhome);
1.860 raeburn 993: }
994: } else {
995: if (!$uhome) {
996: if (defined(&domain($udom,'primary'))) {
997: $uhome=&domain($udom,'primary');
998: }
999: }
1000: }
1001: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1002: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1003: my %returnhash;
1.875 albertel 1004: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1005: return %returnhash;
1006: }
1.806 raeburn 1007: my @pairs=split(/\&/,$rep);
1008: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1009: return @pairs;
1010: }
1011: my $i=0;
1012: foreach my $item (@$storearr) {
1013: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1014: $i++;
1015: }
1016: return %returnhash;
1017: } else {
1.880 banghart 1018: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1019: }
1020: }
1021:
1022: # -------------------------------------------- put items in domain db files
1023:
1024: sub put_dom {
1.860 raeburn 1025: my ($namespace,$storehash,$udom,$uhome)=@_;
1026: if (!$udom) {
1027: $udom=$env{'user.domain'};
1028: if (defined(&domain($udom,'primary'))) {
1029: $uhome=&domain($udom,'primary');
1030: } else {
1.874 albertel 1031: undef($uhome);
1.860 raeburn 1032: }
1033: } else {
1034: if (!$uhome) {
1035: if (defined(&domain($udom,'primary'))) {
1036: $uhome=&domain($udom,'primary');
1037: }
1038: }
1039: }
1040: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1041: my $items='';
1042: foreach my $item (keys(%$storehash)) {
1043: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1044: }
1045: $items=~s/\&$//;
1046: return &reply("putdom:$udom:$namespace:$items",$uhome);
1047: } else {
1.860 raeburn 1048: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1049: }
1050: }
1051:
1.1023 raeburn 1052: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1053: sub newput_dom {
1.1023 raeburn 1054: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1055: my $result;
1056: if (!$udom) {
1057: $udom=$env{'user.domain'};
1058: }
1.1023 raeburn 1059: if ($udom) {
1060: my $uname = &get_domainconfiguser($udom);
1061: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1062: }
1063: return $result;
1064: }
1065:
1.1023 raeburn 1066: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1067: sub del_dom {
1.1023 raeburn 1068: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1069: if (ref($storearr) eq 'ARRAY') {
1070: if (!$udom) {
1071: $udom=$env{'user.domain'};
1072: }
1.1023 raeburn 1073: if ($udom) {
1074: my $uname = &get_domainconfiguser($udom);
1075: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1076: }
1077: }
1078: }
1079:
1.1023 raeburn 1080: # ----------------------------------construct domainconfig user for a domain
1081: sub get_domainconfiguser {
1082: my ($udom) = @_;
1083: return $udom.'-domainconfig';
1084: }
1085:
1.837 raeburn 1086: sub retrieve_inst_usertypes {
1087: my ($udom) = @_;
1088: my (%returnhash,@order);
1.989 raeburn 1089: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1090: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1091: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1092: %returnhash = %{$domdefs{'inststatustypes'}};
1093: @order = @{$domdefs{'inststatusorder'}};
1094: } else {
1095: if (defined(&domain($udom,'primary'))) {
1096: my $uhome=&domain($udom,'primary');
1097: my $rep=&reply("inst_usertypes:$udom",$uhome);
1098: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1099: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1100: return (\%returnhash,\@order);
1101: }
1102: my ($hashitems,$orderitems) = split(/:/,$rep);
1103: my @pairs=split(/\&/,$hashitems);
1104: foreach my $item (@pairs) {
1105: my ($key,$value)=split(/=/,$item,2);
1106: $key = &unescape($key);
1107: next if ($key =~ /^error: 2 /);
1108: $returnhash{$key}=&thaw_unescape($value);
1109: }
1110: my @esc_order = split(/\&/,$orderitems);
1111: foreach my $item (@esc_order) {
1112: push(@order,&unescape($item));
1113: }
1114: } else {
1115: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1116: }
1117: }
1118: return (\%returnhash,\@order);
1119: }
1120:
1.868 raeburn 1121: sub is_domainimage {
1122: my ($url) = @_;
1123: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1124: if (&domain($1) ne '') {
1125: return '1';
1126: }
1127: }
1128: return;
1129: }
1130:
1.899 raeburn 1131: sub inst_directory_query {
1132: my ($srch) = @_;
1133: my $udom = $srch->{'srchdomain'};
1134: my %results;
1135: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1136: my $outcome;
1.899 raeburn 1137: if ($homeserver ne '') {
1.904 albertel 1138: my $queryid=&reply("querysend:instdirsearch:".
1139: &escape($srch->{'srchby'}).':'.
1140: &escape($srch->{'srchterm'}).':'.
1141: &escape($srch->{'srchtype'}),$homeserver);
1142: my $host=&hostname($homeserver);
1143: if ($queryid !~/^\Q$host\E\_/) {
1144: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1145: return;
1146: }
1147: my $response = &get_query_reply($queryid);
1148: my $maxtries = 5;
1149: my $tries = 1;
1150: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1151: $response = &get_query_reply($queryid);
1152: $tries ++;
1153: }
1154:
1155: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1156: if ($response eq 'unavailable') {
1157: $outcome = $response;
1158: } else {
1159: $outcome = 'ok';
1160: my @matches = split(/\n/,$response);
1161: foreach my $match (@matches) {
1162: my ($key,$value) = split(/=/,$match);
1163: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1164: }
1.899 raeburn 1165: }
1166: }
1167: }
1.909 raeburn 1168: return ($outcome,%results);
1.899 raeburn 1169: }
1170:
1171: sub usersearch {
1172: my ($srch) = @_;
1173: my $dom = $srch->{'srchdomain'};
1174: my %results;
1175: my %libserv = &all_library();
1176: my $query = 'usersearch';
1177: foreach my $tryserver (keys(%libserv)) {
1178: if (&host_domain($tryserver) eq $dom) {
1179: my $host=&hostname($tryserver);
1180: my $queryid=
1.911 raeburn 1181: &reply("querysend:".&escape($query).':'.
1182: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1183: &escape($srch->{'srchtype'}).':'.
1184: &escape($srch->{'srchterm'}),$tryserver);
1185: if ($queryid !~/^\Q$host\E\_/) {
1186: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1187: next;
1.899 raeburn 1188: }
1189: my $reply = &get_query_reply($queryid);
1190: my $maxtries = 1;
1191: my $tries = 1;
1192: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1193: $reply = &get_query_reply($queryid);
1194: $tries ++;
1195: }
1196: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1197: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1198: } else {
1.911 raeburn 1199: my @matches;
1200: if ($reply =~ /\n/) {
1201: @matches = split(/\n/,$reply);
1202: } else {
1203: @matches = split(/\&/,$reply);
1204: }
1.899 raeburn 1205: foreach my $match (@matches) {
1206: my ($uname,$udom,%userhash);
1.911 raeburn 1207: foreach my $entry (split(/:/,$match)) {
1208: my ($key,$value) =
1209: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1210: $userhash{$key} = $value;
1211: if ($key eq 'username') {
1212: $uname = $value;
1213: } elsif ($key eq 'domain') {
1214: $udom = $value;
1.911 raeburn 1215: }
1.899 raeburn 1216: }
1217: $results{$uname.':'.$udom} = \%userhash;
1218: }
1219: }
1220: }
1221: }
1222: return %results;
1223: }
1224:
1.912 raeburn 1225: sub get_instuser {
1226: my ($udom,$uname,$id) = @_;
1227: my $homeserver = &domain($udom,'primary');
1228: my ($outcome,%results);
1229: if ($homeserver ne '') {
1230: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1231: &escape($id).':'.&escape($udom),$homeserver);
1232: my $host=&hostname($homeserver);
1233: if ($queryid !~/^\Q$host\E\_/) {
1234: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1235: return;
1236: }
1237: my $response = &get_query_reply($queryid);
1238: my $maxtries = 5;
1239: my $tries = 1;
1240: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1241: $response = &get_query_reply($queryid);
1242: $tries ++;
1243: }
1244: if (!&error($response) && $response ne 'refused') {
1245: if ($response eq 'unavailable') {
1246: $outcome = $response;
1247: } else {
1248: $outcome = 'ok';
1249: my @matches = split(/\n/,$response);
1250: foreach my $match (@matches) {
1251: my ($key,$value) = split(/=/,$match);
1252: $results{&unescape($key)} = &thaw_unescape($value);
1253: }
1254: }
1255: }
1256: }
1257: my %userinfo;
1258: if (ref($results{$uname}) eq 'HASH') {
1259: %userinfo = %{$results{$uname}};
1260: }
1261: return ($outcome,%userinfo);
1262: }
1263:
1264: sub inst_rulecheck {
1.923 raeburn 1265: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1266: my %returnhash;
1267: if ($udom ne '') {
1268: if (ref($rules) eq 'ARRAY') {
1269: @{$rules} = map {&escape($_);} (@{$rules});
1270: my $rulestr = join(':',@{$rules});
1271: my $homeserver=&domain($udom,'primary');
1272: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1273: my $response;
1274: if ($item eq 'username') {
1275: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1276: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1277: $homeserver));
1.923 raeburn 1278: } elsif ($item eq 'id') {
1279: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1280: ':'.&escape($id).':'.$rulestr,
1281: $homeserver));
1.945 raeburn 1282: } elsif ($item eq 'selfcreate') {
1283: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1284: &escape($udom).':'.&escape($uname).
1285: ':'.$rulestr,$homeserver));
1.923 raeburn 1286: }
1.912 raeburn 1287: if ($response ne 'refused') {
1288: my @pairs=split(/\&/,$response);
1289: foreach my $item (@pairs) {
1290: my ($key,$value)=split(/=/,$item,2);
1291: $key = &unescape($key);
1292: next if ($key =~ /^error: 2 /);
1293: $returnhash{$key}=&thaw_unescape($value);
1294: }
1295: }
1296: }
1297: }
1298: }
1299: return %returnhash;
1300: }
1301:
1302: sub inst_userrules {
1.923 raeburn 1303: my ($udom,$check) = @_;
1.912 raeburn 1304: my (%ruleshash,@ruleorder);
1305: if ($udom ne '') {
1306: my $homeserver=&domain($udom,'primary');
1307: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1308: my $response;
1309: if ($check eq 'id') {
1310: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1311: $homeserver);
1.943 raeburn 1312: } elsif ($check eq 'email') {
1313: $response=&reply('instemailrules:'.&escape($udom),
1314: $homeserver);
1.923 raeburn 1315: } else {
1316: $response=&reply('instuserrules:'.&escape($udom),
1317: $homeserver);
1318: }
1.912 raeburn 1319: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1320: ($response ne 'unknown_cmd') &&
1.912 raeburn 1321: ($response ne 'no_such_host')) {
1322: my ($hashitems,$orderitems) = split(/:/,$response);
1323: my @pairs=split(/\&/,$hashitems);
1324: foreach my $item (@pairs) {
1325: my ($key,$value)=split(/=/,$item,2);
1326: $key = &unescape($key);
1327: next if ($key =~ /^error: 2 /);
1328: $ruleshash{$key}=&thaw_unescape($value);
1329: }
1330: my @esc_order = split(/\&/,$orderitems);
1331: foreach my $item (@esc_order) {
1332: push(@ruleorder,&unescape($item));
1333: }
1334: }
1335: }
1336: }
1337: return (\%ruleshash,\@ruleorder);
1338: }
1339:
1.976 raeburn 1340: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1341:
1342: sub get_domain_defaults {
1343: my ($domain) = @_;
1344: my $cachetime = 60*60*24;
1345: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1346: if (defined($cached)) {
1347: if (ref($result) eq 'HASH') {
1348: return %{$result};
1349: }
1350: }
1351: my %domdefaults;
1352: my %domconfig =
1.989 raeburn 1353: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1354: 'requestcourses','inststatus',
1355: 'coursedefaults'],$domain);
1.943 raeburn 1356: if (ref($domconfig{'defaults'}) eq 'HASH') {
1357: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1358: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1359: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1360: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1361: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1362: } else {
1363: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1364: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1365: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1366: }
1.976 raeburn 1367: if (ref($domconfig{'quotas'}) eq 'HASH') {
1368: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1369: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1370: } else {
1371: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1372: }
1373: my @usertools = ('aboutme','blog','portfolio');
1374: foreach my $item (@usertools) {
1375: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1376: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1377: }
1378: }
1379: }
1.985 raeburn 1380: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1381: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1382: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1383: }
1384: }
1.989 raeburn 1385: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1386: foreach my $item ('inststatustypes','inststatusorder') {
1387: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1388: }
1389: }
1.1047 raeburn 1390: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1391: foreach my $item ('canuse_pdfforms') {
1392: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1393: }
1394: }
1.943 raeburn 1395: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1396: $cachetime);
1397: return %domdefaults;
1398: }
1399:
1.344 www 1400: # --------------------------------------------------- Assign a key to a student
1401:
1402: sub assign_access_key {
1.364 www 1403: #
1404: # a valid key looks like uname:udom#comments
1405: # comments are being appended
1406: #
1.498 www 1407: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1408: $kdom=
1.620 albertel 1409: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1410: $knum=
1.620 albertel 1411: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1412: $cdom=
1.620 albertel 1413: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1414: $cnum=
1.620 albertel 1415: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1416: $udom=$env{'user.name'} unless (defined($udom));
1417: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1418: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1419: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1420: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1421: # assigned to this person
1422: # - this should not happen,
1.345 www 1423: # unless something went wrong
1424: # the first time around
1425: # ready to assign
1.364 www 1426: $logentry=$1.'; '.$logentry;
1.496 www 1427: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1428: $kdom,$knum) eq 'ok') {
1.345 www 1429: # key now belongs to user
1.346 www 1430: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1431: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1432: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1433: return 'ok';
1434: } else {
1435: return
1436: 'error: Count not permanently assign key, will need to be re-entered later.';
1437: }
1438: } else {
1439: return 'error: Could not assign key, try again later.';
1440: }
1.364 www 1441: } elsif (!$existing{$ckey}) {
1.345 www 1442: # the key does not exist
1443: return 'error: The key does not exist';
1444: } else {
1445: # the key is somebody else's
1446: return 'error: The key is already in use';
1447: }
1.344 www 1448: }
1449:
1.364 www 1450: # ------------------------------------------ put an additional comment on a key
1451:
1452: sub comment_access_key {
1453: #
1454: # a valid key looks like uname:udom#comments
1455: # comments are being appended
1456: #
1457: my ($ckey,$cdom,$cnum,$logentry)=@_;
1458: $cdom=
1.620 albertel 1459: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1460: $cnum=
1.620 albertel 1461: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1462: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1463: if ($existing{$ckey}) {
1464: $existing{$ckey}.='; '.$logentry;
1465: # ready to assign
1.367 www 1466: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1467: $cdom,$cnum) eq 'ok') {
1468: return 'ok';
1469: } else {
1470: return 'error: Count not store comment.';
1471: }
1472: } else {
1473: # the key does not exist
1474: return 'error: The key does not exist';
1475: }
1476: }
1477:
1.344 www 1478: # ------------------------------------------------------ Generate a set of keys
1479:
1480: sub generate_access_keys {
1.364 www 1481: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1482: $cdom=
1.620 albertel 1483: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1484: $cnum=
1.620 albertel 1485: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1486: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1487: unless (($cdom) && ($cnum)) { return 0; }
1488: if ($number>10000) { return 0; }
1489: sleep(2); # make sure don't get same seed twice
1490: srand(time()^($$+($$<<15))); # from "Programming Perl"
1491: my $total=0;
1492: for (my $i=1;$i<=$number;$i++) {
1493: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1494: sprintf("%lx",int(100000*rand)).'-'.
1495: sprintf("%lx",int(100000*rand));
1496: $newkey=~s/1/g/g; # folks mix up 1 and l
1497: $newkey=~s/0/h/g; # and also 0 and O
1498: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1499: if ($existing{$newkey}) {
1500: $i--;
1501: } else {
1.364 www 1502: if (&put('accesskeys',
1503: { $newkey => '# generated '.localtime().
1.620 albertel 1504: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1505: '; '.$logentry },
1506: $cdom,$cnum) eq 'ok') {
1.344 www 1507: $total++;
1508: }
1509: }
1510: }
1.620 albertel 1511: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1512: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1513: return $total;
1514: }
1515:
1516: # ------------------------------------------------------- Validate an accesskey
1517:
1518: sub validate_access_key {
1519: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1520: $cdom=
1.620 albertel 1521: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1522: $cnum=
1.620 albertel 1523: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1524: $udom=$env{'user.domain'} unless (defined($udom));
1525: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1526: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1527: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1528: }
1529:
1530: # ------------------------------------- Find the section of student in a course
1.652 albertel 1531: sub devalidate_getsection_cache {
1532: my ($udom,$unam,$courseid)=@_;
1533: my $hashid="$udom:$unam:$courseid";
1534: &devalidate_cache_new('getsection',$hashid);
1535: }
1.298 matthew 1536:
1.815 albertel 1537: sub courseid_to_courseurl {
1538: my ($courseid) = @_;
1539: #already url style courseid
1540: return $courseid if ($courseid =~ m{^/});
1541:
1542: if (exists($env{'course.'.$courseid.'.num'})) {
1543: my $cnum = $env{'course.'.$courseid.'.num'};
1544: my $cdom = $env{'course.'.$courseid.'.domain'};
1545: return "/$cdom/$cnum";
1546: }
1547:
1548: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1549: if (exists($courseinfo{'num'})) {
1550: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1551: }
1552:
1553: return undef;
1554: }
1555:
1.298 matthew 1556: sub getsection {
1557: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1558: my $cachetime=1800;
1.551 albertel 1559:
1560: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1561: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1562: if (defined($cached)) { return $result; }
1563:
1.298 matthew 1564: my %Pending;
1565: my %Expired;
1566: #
1567: # Each role can either have not started yet (pending), be active,
1568: # or have expired.
1569: #
1570: # If there is an active role, we are done.
1571: #
1572: # If there is more than one role which has not started yet,
1573: # choose the one which will start sooner
1574: # If there is one role which has not started yet, return it.
1575: #
1576: # If there is more than one expired role, choose the one which ended last.
1577: # If there is a role which has expired, return it.
1578: #
1.815 albertel 1579: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1580: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1581: foreach my $key (keys(%roleshash)) {
1.479 albertel 1582: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1583: my $section=$1;
1584: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1585: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1586: my $now=time;
1.548 albertel 1587: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1588: $Expired{$end}=$section;
1589: next;
1590: }
1.548 albertel 1591: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1592: $Pending{$start}=$section;
1593: next;
1594: }
1.599 albertel 1595: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1596: }
1597: #
1598: # Presumedly there will be few matching roles from the above
1599: # loop and the sorting time will be negligible.
1600: if (scalar(keys(%Pending))) {
1601: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1602: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1603: }
1604: if (scalar(keys(%Expired))) {
1605: my @sorted = sort {$a <=> $b} keys(%Expired);
1606: my $time = pop(@sorted);
1.599 albertel 1607: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1608: }
1.599 albertel 1609: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1610: }
1.70 www 1611:
1.599 albertel 1612: sub save_cache {
1613: &purge_remembered();
1.722 albertel 1614: #&Apache::loncommon::validate_page();
1.620 albertel 1615: undef(%env);
1.780 albertel 1616: undef($env_loaded);
1.599 albertel 1617: }
1.452 albertel 1618:
1.599 albertel 1619: my $to_remember=-1;
1620: my %remembered;
1621: my %accessed;
1622: my $kicks=0;
1623: my $hits=0;
1.849 albertel 1624: sub make_key {
1625: my ($name,$id) = @_;
1.872 albertel 1626: if (length($id) > 65
1627: && length(&escape($id)) > 200) {
1628: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1629: }
1.849 albertel 1630: return &escape($name.':'.$id);
1631: }
1632:
1.599 albertel 1633: sub devalidate_cache_new {
1634: my ($name,$id,$debug) = @_;
1635: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1636: $id=&make_key($name,$id);
1.599 albertel 1637: $memcache->delete($id);
1638: delete($remembered{$id});
1639: delete($accessed{$id});
1640: }
1641:
1642: sub is_cached_new {
1643: my ($name,$id,$debug) = @_;
1.849 albertel 1644: $id=&make_key($name,$id);
1.599 albertel 1645: if (exists($remembered{$id})) {
1646: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1647: $accessed{$id}=[&gettimeofday()];
1648: $hits++;
1649: return ($remembered{$id},1);
1650: }
1651: my $value = $memcache->get($id);
1652: if (!(defined($value))) {
1653: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1654: return (undef,undef);
1.416 albertel 1655: }
1.599 albertel 1656: if ($value eq '__undef__') {
1657: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1658: $value=undef;
1659: }
1660: &make_room($id,$value,$debug);
1661: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1662: return ($value,1);
1663: }
1664:
1665: sub do_cache_new {
1666: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1667: $id=&make_key($name,$id);
1.599 albertel 1668: my $setvalue=$value;
1669: if (!defined($setvalue)) {
1670: $setvalue='__undef__';
1671: }
1.623 albertel 1672: if (!defined($time) ) {
1673: $time=600;
1674: }
1.599 albertel 1675: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1676: my $result = $memcache->set($id,$setvalue,$time);
1677: if (! $result) {
1.872 albertel 1678: &logthis("caching of id -> $id failed");
1.910 albertel 1679: $memcache->disconnect_all();
1.872 albertel 1680: }
1.600 albertel 1681: # need to make a copy of $value
1.919 albertel 1682: &make_room($id,$value,$debug);
1.599 albertel 1683: return $value;
1684: }
1685:
1686: sub make_room {
1687: my ($id,$value,$debug)=@_;
1.919 albertel 1688:
1689: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1690: : $value;
1.599 albertel 1691: if ($to_remember<0) { return; }
1692: $accessed{$id}=[&gettimeofday()];
1693: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1694: my $to_kick;
1695: my $max_time=0;
1696: foreach my $other (keys(%accessed)) {
1697: if (&tv_interval($accessed{$other}) > $max_time) {
1698: $to_kick=$other;
1699: $max_time=&tv_interval($accessed{$other});
1700: }
1701: }
1702: delete($remembered{$to_kick});
1703: delete($accessed{$to_kick});
1704: $kicks++;
1705: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1706: return;
1707: }
1708:
1.599 albertel 1709: sub purge_remembered {
1.604 albertel 1710: #&logthis("Tossing ".scalar(keys(%remembered)));
1711: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1712: undef(%remembered);
1713: undef(%accessed);
1.428 albertel 1714: }
1.70 www 1715: # ------------------------------------- Read an entry from a user's environment
1716:
1717: sub userenvironment {
1718: my ($udom,$unam,@what)=@_;
1.976 raeburn 1719: my $items;
1720: foreach my $item (@what) {
1721: $items.=&escape($item).'&';
1722: }
1723: $items=~s/\&$//;
1.70 www 1724: my %returnhash=();
1.1009 raeburn 1725: my $uhome = &homeserver($unam,$udom);
1726: unless ($uhome eq 'no_host') {
1727: my @answer=split(/\&/,
1728: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1729: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1730: return %returnhash;
1731: }
1.1009 raeburn 1732: my $i;
1733: for ($i=0;$i<=$#what;$i++) {
1734: $returnhash{$what[$i]}=&unescape($answer[$i]);
1735: }
1.70 www 1736: }
1737: return %returnhash;
1.1 albertel 1738: }
1739:
1.617 albertel 1740: # ---------------------------------------------------------- Get a studentphoto
1741: sub studentphoto {
1742: my ($udom,$unam,$ext) = @_;
1743: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1744: if (defined($env{'request.course.id'})) {
1.708 raeburn 1745: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1746: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1747: return(&retrievestudentphoto($udom,$unam,$ext));
1748: } else {
1749: my ($result,$perm_reqd)=
1.707 albertel 1750: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1751: if ($result eq 'ok') {
1752: if (!($perm_reqd eq 'yes')) {
1753: return(&retrievestudentphoto($udom,$unam,$ext));
1754: }
1755: }
1756: }
1757: }
1758: } else {
1759: my ($result,$perm_reqd) =
1.707 albertel 1760: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1761: if ($result eq 'ok') {
1762: if (!($perm_reqd eq 'yes')) {
1763: return(&retrievestudentphoto($udom,$unam,$ext));
1764: }
1765: }
1766: }
1767: return '/adm/lonKaputt/lonlogo_broken.gif';
1768: }
1769:
1770: sub retrievestudentphoto {
1771: my ($udom,$unam,$ext,$type) = @_;
1772: my $home=&Apache::lonnet::homeserver($unam,$udom);
1773: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1774: if ($ret eq 'ok') {
1775: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1776: if ($type eq 'thumbnail') {
1777: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1778: }
1779: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1780: return $tokenurl;
1781: } else {
1782: if ($type eq 'thumbnail') {
1783: return '/adm/lonKaputt/genericstudent_tn.gif';
1784: } else {
1785: return '/adm/lonKaputt/lonlogo_broken.gif';
1786: }
1.617 albertel 1787: }
1788: }
1789:
1.263 www 1790: # -------------------------------------------------------------------- New chat
1791:
1792: sub chatsend {
1.724 raeburn 1793: my ($newentry,$anon,$group)=@_;
1.620 albertel 1794: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1795: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1796: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1797: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1798: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1799: &escape($newentry)).':'.$group,$chome);
1.292 www 1800: }
1801:
1802: # ------------------------------------------ Find current version of a resource
1803:
1804: sub getversion {
1805: my $fname=&clutter(shift);
1806: unless ($fname=~/^\/res\//) { return -1; }
1807: return ¤tversion(&filelocation('',$fname));
1808: }
1809:
1810: sub currentversion {
1811: my $fname=shift;
1.599 albertel 1812: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1813: if (defined($cached)) { return $result; }
1.292 www 1814: my $author=$fname;
1815: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1816: my ($udom,$uname)=split(/\//,$author);
1817: my $home=homeserver($uname,$udom);
1818: if ($home eq 'no_host') {
1819: return -1;
1820: }
1821: my $answer=reply("currentversion:$fname",$home);
1822: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1823: return -1;
1824: }
1.599 albertel 1825: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1826: }
1827:
1.1 albertel 1828: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1829:
1.1 albertel 1830: sub subscribe {
1831: my $fname=shift;
1.761 raeburn 1832: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1833: $fname=~s/[\n\r]//g;
1.1 albertel 1834: my $author=$fname;
1835: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1836: my ($udom,$uname)=split(/\//,$author);
1837: my $home=homeserver($uname,$udom);
1.335 albertel 1838: if ($home eq 'no_host') {
1839: return 'not_found';
1.1 albertel 1840: }
1841: my $answer=reply("sub:$fname",$home);
1.64 www 1842: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1843: $answer.=' by '.$home;
1844: }
1.1 albertel 1845: return $answer;
1846: }
1847:
1.8 www 1848: # -------------------------------------------------------------- Replicate file
1849:
1850: sub repcopy {
1851: my $filename=shift;
1.23 www 1852: $filename=~s/\/+/\//g;
1.607 raeburn 1853: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1854: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1855: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1856: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1857: return &repcopy_userfile($filename);
1858: }
1.532 albertel 1859: $filename=~s/[\n\r]//g;
1.8 www 1860: my $transname="$filename.in.transfer";
1.828 www 1861: # FIXME: this should flock
1.607 raeburn 1862: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1863: my $remoteurl=subscribe($filename);
1.64 www 1864: if ($remoteurl =~ /^con_lost by/) {
1865: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1866: return 'unavailable';
1.8 www 1867: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1868: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1869: return 'not_found';
1.64 www 1870: } elsif ($remoteurl =~ /^rejected by/) {
1871: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1872: return 'forbidden';
1.20 www 1873: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1874: return 'ok';
1.8 www 1875: } else {
1.290 www 1876: my $author=$filename;
1877: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1878: my ($udom,$uname)=split(/\//,$author);
1879: my $home=homeserver($uname,$udom);
1880: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1881: my @parts=split(/\//,$filename);
1882: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1883: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1884: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1885: return 'bad_request';
1.8 www 1886: }
1887: my $count;
1888: for ($count=5;$count<$#parts;$count++) {
1889: $path.="/$parts[$count]";
1890: if ((-e $path)!=1) {
1891: mkdir($path,0777);
1892: }
1893: }
1894: my $ua=new LWP::UserAgent;
1895: my $request=new HTTP::Request('GET',"$remoteurl");
1896: my $response=$ua->request($request,$transname);
1897: if ($response->is_error()) {
1898: unlink($transname);
1899: my $message=$response->status_line;
1.672 albertel 1900: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1901: ." LWP get: $message: $filename</font>");
1.607 raeburn 1902: return 'unavailable';
1.8 www 1903: } else {
1.16 www 1904: if ($remoteurl!~/\.meta$/) {
1905: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1906: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1907: if ($mresponse->is_error()) {
1908: unlink($filename.'.meta');
1909: &logthis(
1.672 albertel 1910: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1911: }
1912: }
1.8 www 1913: rename($transname,$filename);
1.607 raeburn 1914: return 'ok';
1.8 www 1915: }
1.290 www 1916: }
1.8 www 1917: }
1.330 www 1918: }
1919:
1920: # ------------------------------------------------ Get server side include body
1921: sub ssi_body {
1.381 albertel 1922: my ($filelink,%form)=@_;
1.606 matthew 1923: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1924: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1925: }
1.953 www 1926: my $output='';
1927: my $response;
1.980 raeburn 1928: if ($filelink=~/^https?\:/) {
1.954 raeburn 1929: ($output,$response)=&externalssi($filelink);
1.953 www 1930: } else {
1.1004 droeschl 1931: $filelink .= $filelink=~/\?/ ? '&' : '?';
1932: $filelink .= 'inhibitmenu=yes';
1.953 www 1933: ($output,$response)=&ssi($filelink,%form);
1934: }
1.778 albertel 1935: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1936: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1937: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1938: if (wantarray) {
1939: return ($output, $response);
1940: } else {
1941: return $output;
1942: }
1.8 www 1943: }
1944:
1.15 www 1945: # --------------------------------------------------------- Server Side Include
1946:
1.782 albertel 1947: sub absolute_url {
1948: my ($host_name) = @_;
1949: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1950: if ($host_name eq '') {
1951: $host_name = $ENV{'SERVER_NAME'};
1952: }
1953: return $protocol.$host_name;
1954: }
1955:
1.942 foxr 1956: #
1957: # Server side include.
1958: # Parameters:
1959: # fn Possibly encrypted resource name/id.
1960: # form Hash that describes how the rendering should be done
1961: # and other things.
1.944 foxr 1962: # Returns:
1.950 raeburn 1963: # Scalar context: The content of the response.
1964: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1965: #
1.15 www 1966: sub ssi {
1967:
1.944 foxr 1968: my ($fn,%form)=@_;
1.15 www 1969: my $ua=new LWP::UserAgent;
1.23 www 1970: my $request;
1.711 albertel 1971:
1972: $form{'no_update_last_known'}=1;
1.895 albertel 1973: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1974: if (%form) {
1.782 albertel 1975: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 1976: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 1977: } else {
1.782 albertel 1978: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1979: }
1980:
1.15 www 1981: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1982: my $response=$ua->request($request);
1983:
1.944 foxr 1984: if (wantarray) {
1985: return ($response->content, $response);
1986: } else {
1987: return $response->content;
1.942 foxr 1988: }
1.324 www 1989: }
1990:
1991: sub externalssi {
1992: my ($url)=@_;
1993: my $ua=new LWP::UserAgent;
1994: my $request=new HTTP::Request('GET',$url);
1995: my $response=$ua->request($request);
1.954 raeburn 1996: if (wantarray) {
1997: return ($response->content, $response);
1998: } else {
1999: return $response->content;
2000: }
1.15 www 2001: }
1.254 www 2002:
1.492 albertel 2003: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2004:
2005: sub allowuploaded {
2006: my ($srcurl,$url)=@_;
2007: $url=&clutter(&declutter($url));
2008: my $dir=$url;
2009: $dir=~s/\/[^\/]+$//;
2010: my %httpref=();
2011: my $httpurl=&hreflocation('',$url);
2012: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2013: &Apache::lonnet::appenv(\%httpref);
1.254 www 2014: }
1.477 raeburn 2015:
1.478 albertel 2016: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2017: # input: action, courseID, current domain, intended
1.637 raeburn 2018: # path to file, source of file, instruction to parse file for objects,
2019: # ref to hash for embedded objects,
2020: # ref to hash for codebase of java objects.
2021: #
1.485 raeburn 2022: # output: url to file (if action was uploaddoc),
2023: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2024: #
1.478 albertel 2025: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2026: # course.
1.477 raeburn 2027: #
1.478 albertel 2028: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2029: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2030: # course's home server.
1.477 raeburn 2031: #
1.478 albertel 2032: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2033: # be copied from $source (current location) to
2034: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2035: # and will then be copied to
2036: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2037: # course's home server.
1.485 raeburn 2038: #
1.481 raeburn 2039: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2040: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2041: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2042: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2043: # in course's home server.
1.637 raeburn 2044: #
1.477 raeburn 2045:
2046: sub process_coursefile {
1.638 albertel 2047: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2048: my $fetchresult;
1.638 albertel 2049: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2050: if ($action eq 'propagate') {
1.638 albertel 2051: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2052: $home);
1.481 raeburn 2053: } else {
1.477 raeburn 2054: my $fpath = '';
2055: my $fname = $file;
1.478 albertel 2056: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2057: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2058: my $filepath = &build_filepath($fpath);
1.481 raeburn 2059: if ($action eq 'copy') {
2060: if ($source eq '') {
2061: $fetchresult = 'no source file';
2062: return $fetchresult;
2063: } else {
2064: my $destination = $filepath.'/'.$fname;
2065: rename($source,$destination);
2066: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2067: $home);
1.481 raeburn 2068: }
2069: } elsif ($action eq 'uploaddoc') {
2070: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2071: print $fh $env{'form.'.$source};
1.481 raeburn 2072: close($fh);
1.637 raeburn 2073: if ($parser eq 'parse') {
1.1024 raeburn 2074: my $mm = new File::MMagic;
2075: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2076: if ($mime_type eq 'text/html') {
2077: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2078: unless ($parse_result eq 'ok') {
2079: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2080: }
1.637 raeburn 2081: }
2082: }
1.477 raeburn 2083: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2084: $home);
1.481 raeburn 2085: if ($fetchresult eq 'ok') {
2086: return '/uploaded/'.$fpath.'/'.$fname;
2087: } else {
2088: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2089: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2090: return '/adm/notfound.html';
2091: }
1.477 raeburn 2092: }
2093: }
1.485 raeburn 2094: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2095: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2096: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2097: }
2098: return $fetchresult;
2099: }
2100:
1.637 raeburn 2101: sub build_filepath {
2102: my ($fpath) = @_;
2103: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2104: unless ($fpath eq '') {
2105: my @parts=split('/',$fpath);
2106: foreach my $part (@parts) {
2107: $filepath.= '/'.$part;
2108: if ((-e $filepath)!=1) {
2109: mkdir($filepath,0777);
2110: }
2111: }
2112: }
2113: return $filepath;
2114: }
2115:
2116: sub store_edited_file {
1.638 albertel 2117: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2118: my $file = $primary_url;
2119: $file =~ s#^/uploaded/$docudom/$docuname/##;
2120: my $fpath = '';
2121: my $fname = $file;
2122: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2123: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2124: my $filepath = &build_filepath($fpath);
2125: open(my $fh,'>'.$filepath.'/'.$fname);
2126: print $fh $content;
2127: close($fh);
1.638 albertel 2128: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2129: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2130: $home);
1.637 raeburn 2131: if ($$fetchresult eq 'ok') {
2132: return '/uploaded/'.$fpath.'/'.$fname;
2133: } else {
1.638 albertel 2134: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2135: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2136: return '/adm/notfound.html';
2137: }
2138: }
2139:
1.531 albertel 2140: sub clean_filename {
1.831 albertel 2141: my ($fname,$args)=@_;
1.315 www 2142: # Replace Windows backslashes by forward slashes
1.257 www 2143: $fname=~s/\\/\//g;
1.831 albertel 2144: if (!$args->{'keep_path'}) {
2145: # Get rid of everything but the actual filename
2146: $fname=~s/^.*\/([^\/]+)$/$1/;
2147: }
1.315 www 2148: # Replace spaces by underscores
2149: $fname=~s/\s+/\_/g;
2150: # Replace all other weird characters by nothing
1.831 albertel 2151: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2152: # Replace all .\d. sequences with _\d. so they no longer look like version
2153: # numbers
2154: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2155: return $fname;
2156: }
1.1051 raeburn 2157: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2158: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2159: # image with the same aspect ratio as the original, but with dimensions which do
2160: # not exceed $resizewidth and $resizeheight.
2161:
1.984 neumanie 2162: sub resizeImage {
1.1051 raeburn 2163: my ($img_path,$resizewidth,$resizeheight) = @_;
2164: my $ima = Image::Magick->new;
2165: my $resized;
2166: if (-e $img_path) {
2167: $ima->Read($img_path);
2168: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2169: my $width = $ima->Get('width');
2170: my $height = $ima->Get('height');
2171: if ($width > $resizewidth) {
2172: my $factor = $width/$resizewidth;
2173: my $newheight = $height/$factor;
2174: $ima->Scale(width=>$resizewidth,height=>$newheight);
2175: $resized = 1;
2176: }
2177: }
2178: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2179: my $width = $ima->Get('width');
2180: my $height = $ima->Get('height');
2181: if ($height > $resizeheight) {
2182: my $factor = $height/$resizeheight;
2183: my $newwidth = $width/$factor;
2184: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2185: $resized = 1;
2186: }
2187: }
2188: if ($resized) {
2189: $ima->Write($img_path);
2190: }
2191: }
2192: return;
1.977 amueller 2193: }
2194:
1.608 albertel 2195: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2196: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2197: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2198: # $coursedoc - if true up to the current course
2199: # if false
2200: # $subdir - directory in userfile to store the file into
1.858 raeburn 2201: # $parser - instruction to parse file for objects ($parser = parse)
2202: # $allfiles - reference to hash for embedded objects
2203: # $codebase - reference to hash for codebase of java objects
2204: # $desuname - username for permanent storage of uploaded file
2205: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2206: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2207: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2208: # $resizewidth - width (pixels) to which to resize uploaded image
2209: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2210: #
1.686 albertel 2211: # output: url of file in userspace, or error: <message>
2212: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2213:
1.531 albertel 2214: sub userfileupload {
1.860 raeburn 2215: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2216: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2217: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2218: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2219: $fname=&clean_filename($fname);
1.315 www 2220: # See if there is anything left
1.257 www 2221: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2222: chop($env{'form.'.$formname});
1.523 raeburn 2223: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2224: my $now = time;
2225: my $filepath = 'tmp/helprequests/'.$now;
2226: my @parts=split(/\//,$filepath);
2227: my $fullpath = $perlvar{'lonDaemons'};
2228: for (my $i=0;$i<@parts;$i++) {
2229: $fullpath .= '/'.$parts[$i];
2230: if ((-e $fullpath)!=1) {
2231: mkdir($fullpath,0777);
2232: }
2233: }
2234: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2235: print $fh $env{'form.'.$formname};
1.523 raeburn 2236: close($fh);
1.741 raeburn 2237: return $fullpath.'/'.$fname;
2238: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2239: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2240: '_'.$env{'user.domain'}.'/pending';
2241: my @parts=split(/\//,$filepath);
2242: my $fullpath = $perlvar{'lonDaemons'};
2243: for (my $i=0;$i<@parts;$i++) {
2244: $fullpath .= '/'.$parts[$i];
2245: if ((-e $fullpath)!=1) {
2246: mkdir($fullpath,0777);
2247: }
2248: }
2249: open(my $fh,'>'.$fullpath.'/'.$fname);
2250: print $fh $env{'form.'.$formname};
2251: close($fh);
2252: return $fullpath.'/'.$fname;
1.523 raeburn 2253: }
1.995 raeburn 2254: if ($subdir eq 'scantron') {
2255: $fname = 'scantron_orig_'.$fname;
2256: } else {
1.258 www 2257: # Create the directory if not present
1.995 raeburn 2258: $fname="$subdir/$fname";
2259: }
1.259 www 2260: if ($coursedoc) {
1.638 albertel 2261: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2262: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2263: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2264: return &finishuserfileupload($docuname,$docudom,
2265: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2266: $codebase,$thumbwidth,$thumbheight,
2267: $resizewidth,$resizeheight);
1.481 raeburn 2268: } else {
1.620 albertel 2269: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2270: return &process_coursefile('uploaddoc',$docuname,$docudom,
2271: $fname,$formname,$parser,
2272: $allfiles,$codebase);
1.481 raeburn 2273: }
1.719 banghart 2274: } elsif (defined($destuname)) {
2275: my $docuname=$destuname;
2276: my $docudom=$destudom;
1.860 raeburn 2277: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2278: $parser,$allfiles,$codebase,
1.1051 raeburn 2279: $thumbwidth,$thumbheight,
2280: $resizewidth,$resizeheight);
1.719 banghart 2281:
1.259 www 2282: } else {
1.638 albertel 2283: my $docuname=$env{'user.name'};
2284: my $docudom=$env{'user.domain'};
1.714 raeburn 2285: if (exists($env{'form.group'})) {
2286: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2287: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2288: }
1.860 raeburn 2289: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2290: $parser,$allfiles,$codebase,
1.1051 raeburn 2291: $thumbwidth,$thumbheight,
2292: $resizewidth,$resizeheight);
1.259 www 2293: }
1.271 www 2294: }
2295:
2296: sub finishuserfileupload {
1.860 raeburn 2297: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2298: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2299: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2300: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2301:
1.860 raeburn 2302: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2303: $file=$fname;
2304: if ($fname=~m|/|) {
2305: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2306: $path.=$fnamepath.'/';
2307: }
1.259 www 2308: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2309: my $count;
2310: for ($count=4;$count<=$#parts;$count++) {
2311: $filepath.="/$parts[$count]";
2312: if ((-e $filepath)!=1) {
2313: mkdir($filepath,0777);
2314: }
2315: }
1.984 neumanie 2316:
1.258 www 2317: # Save the file
2318: {
1.701 albertel 2319: if (!open(FH,'>'.$filepath.'/'.$file)) {
2320: &logthis('Failed to create '.$filepath.'/'.$file);
2321: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2322: return '/adm/notfound.html';
2323: }
2324: if (!print FH ($env{'form.'.$formname})) {
2325: &logthis('Failed to write to '.$filepath.'/'.$file);
2326: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2327: return '/adm/notfound.html';
2328: }
1.570 albertel 2329: close(FH);
1.1051 raeburn 2330: if ($resizewidth && $resizeheight) {
2331: my $mm = new File::MMagic;
2332: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2333: if ($mime_type =~ m{^image/}) {
2334: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2335: }
1.977 amueller 2336: }
1.258 www 2337: }
1.637 raeburn 2338: if ($parser eq 'parse') {
1.1024 raeburn 2339: my $mm = new File::MMagic;
2340: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2341: if ($mime_type eq 'text/html') {
2342: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2343: $allfiles,$codebase);
2344: unless ($parse_result eq 'ok') {
2345: &logthis('Failed to parse '.$filepath.$file.
2346: ' for embedded media: '.$parse_result);
2347: }
1.637 raeburn 2348: }
2349: }
1.860 raeburn 2350: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2351: my $input = $filepath.'/'.$file;
2352: my $output = $filepath.'/'.'tn-'.$file;
2353: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2354: system("convert -sample $thumbsize $input $output");
2355: if (-e $filepath.'/'.'tn-'.$file) {
2356: $fetchthumb = 1;
2357: }
2358: }
1.858 raeburn 2359:
1.259 www 2360: # Notify homeserver to grep it
2361: #
1.984 neumanie 2362: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2363: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2364: if ($fetchresult eq 'ok') {
1.860 raeburn 2365: if ($fetchthumb) {
2366: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2367: if ($thumbresult ne 'ok') {
2368: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2369: $docuhome.': '.$thumbresult);
2370: }
2371: }
1.259 www 2372: #
1.258 www 2373: # Return the URL to it
1.494 albertel 2374: return '/uploaded/'.$path.$file;
1.263 www 2375: } else {
1.494 albertel 2376: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2377: ': '.$fetchresult);
1.263 www 2378: return '/adm/notfound.html';
1.858 raeburn 2379: }
1.493 albertel 2380: }
2381:
1.637 raeburn 2382: sub extract_embedded_items {
1.961 raeburn 2383: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2384: my @state = ();
2385: my %javafiles = (
2386: codebase => '',
2387: code => '',
2388: archive => ''
2389: );
2390: my %mediafiles = (
2391: src => '',
2392: movie => '',
2393: );
1.648 raeburn 2394: my $p;
2395: if ($content) {
2396: $p = HTML::LCParser->new($content);
2397: } else {
1.961 raeburn 2398: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2399: }
1.641 albertel 2400: while (my $t=$p->get_token()) {
1.640 albertel 2401: if ($t->[0] eq 'S') {
2402: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2403: push(@state, $tagname);
1.648 raeburn 2404: if (lc($tagname) eq 'allow') {
2405: &add_filetype($allfiles,$attr->{'src'},'src');
2406: }
1.640 albertel 2407: if (lc($tagname) eq 'img') {
2408: &add_filetype($allfiles,$attr->{'src'},'src');
2409: }
1.886 albertel 2410: if (lc($tagname) eq 'a') {
2411: &add_filetype($allfiles,$attr->{'href'},'href');
2412: }
1.645 raeburn 2413: if (lc($tagname) eq 'script') {
2414: if ($attr->{'archive'} =~ /\.jar$/i) {
2415: &add_filetype($allfiles,$attr->{'archive'},'archive');
2416: } else {
2417: &add_filetype($allfiles,$attr->{'src'},'src');
2418: }
2419: }
2420: if (lc($tagname) eq 'link') {
2421: if (lc($attr->{'rel'}) eq 'stylesheet') {
2422: &add_filetype($allfiles,$attr->{'href'},'href');
2423: }
2424: }
1.640 albertel 2425: if (lc($tagname) eq 'object' ||
2426: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2427: foreach my $item (keys(%javafiles)) {
2428: $javafiles{$item} = '';
2429: }
2430: }
2431: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2432: my $name = lc($attr->{'name'});
2433: foreach my $item (keys(%javafiles)) {
2434: if ($name eq $item) {
2435: $javafiles{$item} = $attr->{'value'};
2436: last;
2437: }
2438: }
2439: foreach my $item (keys(%mediafiles)) {
2440: if ($name eq $item) {
2441: &add_filetype($allfiles, $attr->{'value'}, 'value');
2442: last;
2443: }
2444: }
2445: }
2446: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2447: foreach my $item (keys(%javafiles)) {
2448: if ($attr->{$item}) {
2449: $javafiles{$item} = $attr->{$item};
2450: last;
2451: }
2452: }
2453: foreach my $item (keys(%mediafiles)) {
2454: if ($attr->{$item}) {
2455: &add_filetype($allfiles,$attr->{$item},$item);
2456: last;
2457: }
2458: }
2459: }
2460: } elsif ($t->[0] eq 'E') {
2461: my ($tagname) = ($t->[1]);
2462: if ($javafiles{'codebase'} ne '') {
2463: $javafiles{'codebase'} .= '/';
2464: }
2465: if (lc($tagname) eq 'applet' ||
2466: lc($tagname) eq 'object' ||
2467: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2468: ) {
2469: foreach my $item (keys(%javafiles)) {
2470: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2471: my $file=$javafiles{'codebase'}.$javafiles{$item};
2472: &add_filetype($allfiles,$file,$item);
2473: }
2474: }
2475: }
2476: pop @state;
2477: }
2478: }
1.637 raeburn 2479: return 'ok';
2480: }
2481:
1.639 albertel 2482: sub add_filetype {
2483: my ($allfiles,$file,$type)=@_;
2484: if (exists($allfiles->{$file})) {
2485: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2486: push(@{$allfiles->{$file}}, &escape($type));
2487: }
2488: } else {
2489: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2490: }
2491: }
2492:
1.493 albertel 2493: sub removeuploadedurl {
1.984 neumanie 2494: my ($url)=@_;
2495: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2496: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2497: }
2498:
2499: sub removeuserfile {
2500: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2501: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2502: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2503: if ($result eq 'ok') {
1.798 raeburn 2504: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2505: my $metafile = $fname.'.meta';
2506: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2507: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2508: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2509: my $sqlresult =
1.823 albertel 2510: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2511: 'portfolio_metadata',$group,
2512: 'delete');
1.798 raeburn 2513: }
2514: }
2515: return $result;
1.257 www 2516: }
1.15 www 2517:
1.530 albertel 2518: sub mkdiruserfile {
2519: my ($docuname,$docudom,$dir)=@_;
2520: my $home=&homeserver($docuname,$docudom);
2521: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2522: }
2523:
1.531 albertel 2524: sub renameuserfile {
2525: my ($docuname,$docudom,$old,$new)=@_;
2526: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2527: my $result = &reply("renameuserfile:$docudom:$docuname:".
2528: &escape("$old").':'.&escape("$new"),$home);
2529: if ($result eq 'ok') {
2530: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2531: my $oldmeta = $old.'.meta';
2532: my $newmeta = $new.'.meta';
2533: my $metaresult =
2534: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2535: my $url = "/uploaded/$docudom/$docuname/$old";
2536: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2537: my $sqlresult =
1.823 albertel 2538: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2539: 'portfolio_metadata',$group,
2540: 'delete');
1.798 raeburn 2541: }
2542: }
2543: return $result;
1.531 albertel 2544: }
2545:
1.14 www 2546: # ------------------------------------------------------------------------- Log
2547:
2548: sub log {
2549: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2550: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2551: }
2552:
2553: # ------------------------------------------------------------------ Course Log
1.352 www 2554: #
2555: # This routine flushes several buffers of non-mission-critical nature
2556: #
1.157 www 2557:
2558: sub flushcourselogs {
1.352 www 2559: &logthis('Flushing log buffers');
2560: #
2561: # course logs
2562: # This is a log of all transactions in a course, which can be used
2563: # for data mining purposes
2564: #
2565: # It also collects the courseid database, which lists last transaction
2566: # times and course titles for all courseids
2567: #
2568: my %courseidbuffer=();
1.921 raeburn 2569: foreach my $crsid (keys(%courselogs)) {
1.352 www 2570: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2571: &escape($courselogs{$crsid}),
2572: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2573: delete $courselogs{$crsid};
2574: } else {
2575: &logthis('Failed to flush log buffer for '.$crsid);
2576: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2577: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2578: " exceeded maximum size, deleting.</font>");
2579: delete $courselogs{$crsid};
2580: }
1.352 www 2581: }
1.920 raeburn 2582: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2583: 'description' => $coursedescrbuf{$crsid},
2584: 'inst_code' => $courseinstcodebuf{$crsid},
2585: 'type' => $coursetypebuf{$crsid},
2586: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2587: };
1.191 harris41 2588: }
1.352 www 2589: #
2590: # Write course id database (reverse lookup) to homeserver of courses
2591: # Is used in pickcourse
2592: #
1.840 albertel 2593: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2594: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2595: $courseidbuffer{$crs_home},
2596: $crs_home,'timeonly');
1.352 www 2597: }
2598: #
2599: # File accesses
2600: # Writes to the dynamic metadata of resources to get hit counts, etc.
2601: #
1.449 matthew 2602: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2603: if ($entry =~ /___count$/) {
2604: my ($dom,$name);
1.807 albertel 2605: ($dom,$name,undef)=
1.811 albertel 2606: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2607: if (! defined($dom) || $dom eq '' ||
2608: ! defined($name) || $name eq '') {
1.620 albertel 2609: my $cid = $env{'request.course.id'};
2610: $dom = $env{'request.'.$cid.'.domain'};
2611: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2612: }
1.450 matthew 2613: my $value = $accesshash{$entry};
2614: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2615: my %temphash=($url => $value);
1.449 matthew 2616: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2617: if ($result eq 'ok') {
2618: delete $accesshash{$entry};
2619: } elsif ($result eq 'unknown_cmd') {
2620: # Target server has old code running on it.
1.450 matthew 2621: my %temphash=($entry => $value);
1.449 matthew 2622: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2623: delete $accesshash{$entry};
2624: }
2625: }
2626: } else {
1.811 albertel 2627: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2628: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2629: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2630: delete $accesshash{$entry};
2631: }
1.185 www 2632: }
1.191 harris41 2633: }
1.352 www 2634: #
2635: # Roles
2636: # Reverse lookup of user roles for course faculty/staff and co-authorship
2637: #
1.800 albertel 2638: foreach my $entry (keys(%userrolehash)) {
1.351 www 2639: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2640: split(/\:/,$entry);
2641: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2642: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2643: $rudom,$runame) eq 'ok') {
2644: delete $userrolehash{$entry};
2645: }
2646: }
1.662 raeburn 2647: #
2648: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2649: #
2650: my %domrolebuffer = ();
1.1000 raeburn 2651: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2652: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2653: if ($domrolebuffer{$rudom}) {
2654: $domrolebuffer{$rudom}.='&'.&escape($entry).
2655: '='.&escape($domainrolehash{$entry});
2656: } else {
2657: $domrolebuffer{$rudom}.=&escape($entry).
2658: '='.&escape($domainrolehash{$entry});
2659: }
2660: delete $domainrolehash{$entry};
2661: }
2662: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2663: my %servers = &get_servers($dom,'library');
2664: foreach my $tryserver (keys(%servers)) {
2665: unless (&reply('domroleput:'.$dom.':'.
2666: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2667: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2668: }
1.662 raeburn 2669: }
2670: }
1.186 www 2671: $dumpcount++;
1.157 www 2672: }
2673:
2674: sub courselog {
2675: my $what=shift;
1.158 www 2676: $what=time.':'.$what;
1.620 albertel 2677: unless ($env{'request.course.id'}) { return ''; }
2678: $coursedombuf{$env{'request.course.id'}}=
2679: $env{'course.'.$env{'request.course.id'}.'.domain'};
2680: $coursenumbuf{$env{'request.course.id'}}=
2681: $env{'course.'.$env{'request.course.id'}.'.num'};
2682: $coursehombuf{$env{'request.course.id'}}=
2683: $env{'course.'.$env{'request.course.id'}.'.home'};
2684: $coursedescrbuf{$env{'request.course.id'}}=
2685: $env{'course.'.$env{'request.course.id'}.'.description'};
2686: $courseinstcodebuf{$env{'request.course.id'}}=
2687: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2688: $courseownerbuf{$env{'request.course.id'}}=
2689: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2690: $coursetypebuf{$env{'request.course.id'}}=
2691: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2692: if (defined $courselogs{$env{'request.course.id'}}) {
2693: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2694: } else {
1.620 albertel 2695: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2696: }
1.620 albertel 2697: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2698: &flushcourselogs();
2699: }
1.158 www 2700: }
2701:
2702: sub courseacclog {
2703: my $fnsymb=shift;
1.620 albertel 2704: unless ($env{'request.course.id'}) { return ''; }
2705: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2706: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2707: $what.=':POST';
1.583 matthew 2708: # FIXME: Probably ought to escape things....
1.800 albertel 2709: foreach my $key (keys(%env)) {
2710: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2711: my $formitem = $1;
2712: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2713: $what.=':'.$formitem.'='.$env{$key};
2714: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2715: $what.=':'.$formitem.'='.$env{$key};
2716: }
1.158 www 2717: }
1.191 harris41 2718: }
1.583 matthew 2719: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2720: # FIXME: We should not be depending on a form parameter that someone
2721: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2722: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2723: $what.= ':POST';
2724: # FIXME: Probably ought to escape things....
2725: foreach my $element ('courseexp','crsfulltext','crsrelated',
2726: 'crsdiscuss') {
1.620 albertel 2727: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2728: }
2729: }
1.158 www 2730: }
2731: &courselog($what);
1.149 www 2732: }
2733:
1.185 www 2734: sub countacc {
2735: my $url=&declutter(shift);
1.458 matthew 2736: return if (! defined($url) || $url eq '');
1.620 albertel 2737: unless ($env{'request.course.id'}) { return ''; }
2738: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2739: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2740: $accesshash{$key}++;
1.185 www 2741: }
1.349 www 2742:
1.361 www 2743: sub linklog {
2744: my ($from,$to)=@_;
2745: $from=&declutter($from);
2746: $to=&declutter($to);
2747: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2748: $accesshash{$to.'___'.$from.'___goto'}=1;
2749: }
2750:
1.349 www 2751: sub userrolelog {
2752: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2753: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2754: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2755: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2756: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2757: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2758: $userrolehash
2759: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2760: =$tend.':'.$tstart;
1.662 raeburn 2761: }
1.898 albertel 2762: if (($env{'request.role'} =~ /dc\./) &&
2763: (($trole=~/^au/) || ($trole=~/^in/) ||
2764: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2765: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2766: ($trole=~/^co/))) {
1.898 albertel 2767: $userrolehash
2768: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2769: =$tend.':'.$tstart;
2770: }
1.662 raeburn 2771: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2772: ($trole=~/^li/) || ($trole=~/^li/) ||
2773: ($trole=~/^au/) || ($trole=~/^dg/) ||
2774: ($trole=~/^sc/)) {
2775: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2776: $domainrolehash
2777: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2778: = $tend.':'.$tstart;
2779: }
1.351 www 2780: }
2781:
1.957 raeburn 2782: sub courserolelog {
2783: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2784: if (($trole eq 'cc') || ($trole eq 'in') ||
2785: ($trole eq 'ep') || ($trole eq 'ad') ||
2786: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2787: ($trole=~/^cr/) || ($trole eq 'gr') ||
2788: ($trole eq 'co')) {
1.957 raeburn 2789: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2790: my $cdom = $1;
2791: my $cnum = $2;
2792: my $sec = $3;
2793: my $namespace = 'rolelog';
2794: my %storehash = (
2795: role => $trole,
2796: start => $tstart,
2797: end => $tend,
2798: selfenroll => $selfenroll,
2799: context => $context,
2800: );
2801: if ($trole eq 'gr') {
2802: $namespace = 'groupslog';
2803: $storehash{'group'} = $sec;
2804: } else {
2805: $storehash{'section'} = $sec;
2806: }
2807: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2808: if (($trole ne 'st') || ($sec ne '')) {
2809: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2810: }
1.957 raeburn 2811: }
2812: }
2813: return;
2814: }
2815:
1.351 www 2816: sub get_course_adv_roles {
1.948 raeburn 2817: my ($cid,$codes) = @_;
1.620 albertel 2818: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2819: my %coursehash=&coursedescription($cid);
1.988 raeburn 2820: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2821: my %nothide=();
1.800 albertel 2822: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2823: if ($user !~ /:/) {
2824: $nothide{join(':',split(/[\@]/,$user))}=1;
2825: } else {
2826: $nothide{$user}=1;
2827: }
1.470 www 2828: }
1.351 www 2829: my %returnhash=();
2830: my %dumphash=
2831: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2832: my $now=time;
1.997 raeburn 2833: my %privileged;
1.1000 raeburn 2834: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2835: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2836: if (($tstart) && ($tstart<0)) { next; }
2837: if (($tend) && ($tend<$now)) { next; }
2838: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2839: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2840: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2841: unless (ref($privileged{$domain}) eq 'HASH') {
2842: my %dompersonnel =
1.998 raeburn 2843: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2844: $privileged{$domain} = {};
2845: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2846: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2847: foreach my $user (keys(%{$dompersonnel{$server}})) {
2848: my ($trole,$uname,$udom) = split(/:/,$user);
2849: $privileged{$udom}{$uname} = 1;
2850: }
2851: }
2852: }
2853: }
2854: if ((exists($privileged{$domain}{$username})) &&
2855: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2856: if ($role eq 'cr') { next; }
1.948 raeburn 2857: if ($codes) {
2858: if ($section) { $role .= ':'.$section; }
2859: if ($returnhash{$role}) {
2860: $returnhash{$role}.=','.$username.':'.$domain;
2861: } else {
2862: $returnhash{$role}=$username.':'.$domain;
2863: }
1.351 www 2864: } else {
1.988 raeburn 2865: my $key=&plaintext($role,$crstype);
1.973 bisitz 2866: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2867: if ($returnhash{$key}) {
2868: $returnhash{$key}.=','.$username.':'.$domain;
2869: } else {
2870: $returnhash{$key}=$username.':'.$domain;
2871: }
1.351 www 2872: }
1.948 raeburn 2873: }
1.400 www 2874: return %returnhash;
2875: }
2876:
2877: sub get_my_roles {
1.937 raeburn 2878: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2879: unless (defined($uname)) { $uname=$env{'user.name'}; }
2880: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2881: my (%dumphash,%nothide);
1.858 raeburn 2882: if ($context eq 'userroles') {
2883: %dumphash = &dump('roles',$udom,$uname);
2884: } else {
2885: %dumphash=
1.400 www 2886: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2887: if ($hidepriv) {
2888: my %coursehash=&coursedescription($udom.'_'.$uname);
2889: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2890: if ($user !~ /:/) {
2891: $nothide{join(':',split(/[\@]/,$user))} = 1;
2892: } else {
2893: $nothide{$user} = 1;
2894: }
2895: }
2896: }
1.858 raeburn 2897: }
1.400 www 2898: my %returnhash=();
2899: my $now=time;
1.999 raeburn 2900: my %privileged;
1.800 albertel 2901: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2902: my ($role,$tend,$tstart);
2903: if ($context eq 'userroles') {
2904: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2905: } else {
2906: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2907: }
1.400 www 2908: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2909: my $status = 'active';
1.939 raeburn 2910: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2911: $status = 'previous';
2912: }
2913: if (($tstart) && ($now<$tstart)) {
2914: $status = 'future';
2915: }
2916: if (ref($types) eq 'ARRAY') {
2917: if (!grep(/^\Q$status\E$/,@{$types})) {
2918: next;
2919: }
2920: } else {
2921: if ($status ne 'active') {
2922: next;
2923: }
2924: }
1.867 raeburn 2925: my ($rolecode,$username,$domain,$section,$area);
2926: if ($context eq 'userroles') {
2927: ($area,$rolecode) = split(/_/,$entry);
2928: (undef,$domain,$username,$section) = split(/\//,$area);
2929: } else {
2930: ($role,$username,$domain,$section) = split(/\:/,$entry);
2931: }
1.832 raeburn 2932: if (ref($roledoms) eq 'ARRAY') {
2933: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2934: next;
2935: }
2936: }
2937: if (ref($roles) eq 'ARRAY') {
2938: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2939: if ($role =~ /^cr\//) {
2940: if (!grep(/^cr$/,@{$roles})) {
2941: next;
2942: }
2943: } else {
2944: next;
2945: }
1.832 raeburn 2946: }
1.867 raeburn 2947: }
1.937 raeburn 2948: if ($hidepriv) {
1.999 raeburn 2949: if ($context eq 'userroles') {
2950: if ((&privileged($username,$domain)) &&
2951: (!$nothide{$username.':'.$domain})) {
2952: next;
2953: }
2954: } else {
2955: unless (ref($privileged{$domain}) eq 'HASH') {
2956: my %dompersonnel =
2957: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2958: $privileged{$domain} = {};
2959: if (keys(%dompersonnel)) {
2960: foreach my $server (keys(%dompersonnel)) {
2961: if (ref($dompersonnel{$server}) eq 'HASH') {
2962: foreach my $user (keys(%{$dompersonnel{$server}})) {
2963: my ($trole,$uname,$udom) = split(/:/,$user);
2964: $privileged{$udom}{$uname} = $trole;
2965: }
2966: }
2967: }
2968: }
2969: }
2970: if (exists($privileged{$domain}{$username})) {
2971: if (!$nothide{$username.':'.$domain}) {
2972: next;
2973: }
2974: }
1.937 raeburn 2975: }
2976: }
1.933 raeburn 2977: if ($withsec) {
2978: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2979: $tstart.':'.$tend;
2980: } else {
2981: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2982: }
1.832 raeburn 2983: }
1.373 www 2984: return %returnhash;
1.399 www 2985: }
2986:
2987: # ----------------------------------------------------- Frontpage Announcements
2988: #
2989: #
2990:
2991: sub postannounce {
2992: my ($server,$text)=@_;
1.844 albertel 2993: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2994: unless ($text=~/\w/) { $text=''; }
2995: return &reply('setannounce:'.&escape($text),$server);
2996: }
2997:
2998: sub getannounce {
1.448 albertel 2999:
3000: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3001: my $announcement='';
1.800 albertel 3002: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3003: close($fh);
1.399 www 3004: if ($announcement=~/\w/) {
3005: return
3006: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3007: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3008: } else {
3009: return '';
3010: }
3011: } else {
3012: return '';
3013: }
1.351 www 3014: }
1.353 www 3015:
3016: # ---------------------------------------------------------- Course ID routines
3017: # Deal with domain's nohist_courseid.db files
3018: #
3019:
3020: sub courseidput {
1.921 raeburn 3021: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3022: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3023: my $outcome;
3024: if ($caller eq 'timeonly') {
3025: my $cids = '';
3026: foreach my $item (keys(%$storehash)) {
3027: $cids.=&escape($item).'&';
3028: }
3029: $cids=~s/\&$//;
3030: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3031: $coursehome);
3032: } else {
3033: my $items = '';
3034: foreach my $item (keys(%$storehash)) {
3035: $items.= &escape($item).'='.
3036: &freeze_escape($$storehash{$item}).'&';
3037: }
3038: $items=~s/\&$//;
3039: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3040: $coursehome);
1.918 raeburn 3041: }
3042: if ($outcome eq 'unknown_cmd') {
3043: my $what;
3044: foreach my $cid (keys(%$storehash)) {
3045: $what .= &escape($cid).'=';
1.921 raeburn 3046: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3047: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3048: }
3049: $what =~ s/\:$/&/;
3050: }
3051: $what =~ s/\&$//;
3052: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3053: } else {
3054: return $outcome;
3055: }
1.353 www 3056: }
3057:
3058: sub courseiddump {
1.921 raeburn 3059: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3060: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3061: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.2.5 raeburn 3062: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3063: my $as_hash = 1;
3064: my %returnhash;
3065: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3066: my %libserv = &all_library();
3067: foreach my $tryserver (keys(%libserv)) {
3068: if ( ( $hostidflag == 1
3069: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3070: || (!defined($hostidflag)) ) {
3071:
1.918 raeburn 3072: if (($domfilter eq '') ||
3073: (&host_domain($tryserver) eq $domfilter)) {
3074: my $rep =
3075: &reply('courseiddump:'.&host_domain($tryserver).':'.
3076: $sincefilter.':'.&escape($descfilter).':'.
3077: &escape($instcodefilter).':'.&escape($ownerfilter).
3078: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3079: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3080: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3081: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3082: &escape($cc_clone).':'.$cloneonly.':'.
3083: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.2.5 raeburn 3084: &escape($creationcontext).':'.$domcloner,
3085: $tryserver);
1.918 raeburn 3086: my @pairs=split(/\&/,$rep);
3087: foreach my $item (@pairs) {
3088: my ($key,$value)=split(/\=/,$item,2);
3089: $key = &unescape($key);
3090: next if ($key =~ /^error: 2 /);
3091: my $result = &thaw_unescape($value);
3092: if (ref($result) eq 'HASH') {
3093: $returnhash{$key}=$result;
3094: } else {
1.921 raeburn 3095: my @responses = split(/:/,$value);
3096: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3097: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3098: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3099: }
1.1008 raeburn 3100: }
1.353 www 3101: }
3102: }
3103: }
3104: }
3105: return %returnhash;
3106: }
3107:
1.1055 raeburn 3108: sub courselastaccess {
3109: my ($cdom,$cnum,$hostidref) = @_;
3110: my %returnhash;
3111: if ($cdom && $cnum) {
3112: my $chome = &homeserver($cnum,$cdom);
3113: if ($chome ne 'no_host') {
3114: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3115: &extract_lastaccess(\%returnhash,$rep);
3116: }
3117: } else {
3118: if (!$cdom) { $cdom=''; }
3119: my %libserv = &all_library();
3120: foreach my $tryserver (keys(%libserv)) {
3121: if (ref($hostidref) eq 'ARRAY') {
3122: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3123: }
3124: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3125: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3126: &extract_lastaccess(\%returnhash,$rep);
3127: }
3128: }
3129: }
3130: return %returnhash;
3131: }
3132:
3133: sub extract_lastaccess {
3134: my ($returnhash,$rep) = @_;
3135: if (ref($returnhash) eq 'HASH') {
3136: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3137: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3138: $rep eq '') {
3139: my @pairs=split(/\&/,$rep);
3140: foreach my $item (@pairs) {
3141: my ($key,$value)=split(/\=/,$item,2);
3142: $key = &unescape($key);
3143: next if ($key =~ /^error: 2 /);
3144: $returnhash->{$key} = &thaw_unescape($value);
3145: }
3146: }
3147: }
3148: return;
3149: }
3150:
1.658 raeburn 3151: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3152:
3153: sub dcmailput {
1.685 raeburn 3154: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3155: my $status = &Apache::lonnet::critical(
1.740 www 3156: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3157: &escape($message),$server);
1.662 raeburn 3158: return $status;
3159: }
3160:
1.658 raeburn 3161: sub dcmaildump {
3162: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3163: my %returnhash=();
1.846 albertel 3164:
3165: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3166: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3167: &escape($enddate).':';
3168: my @esc_senders=map { &escape($_)} @$senders;
3169: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3170: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3171: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3172: if (($key) && ($value)) {
3173: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3174: }
3175: }
3176: }
3177: return %returnhash;
3178: }
1.662 raeburn 3179: # ---------------------------------------------------------- Domain roles
3180:
3181: sub get_domain_roles {
3182: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3183: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3184: $startdate = '.';
3185: }
1.1018 raeburn 3186: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3187: $enddate = '.';
3188: }
1.922 raeburn 3189: my $rolelist;
3190: if (ref($roles) eq 'ARRAY') {
3191: $rolelist = join(':',@{$roles});
3192: }
1.662 raeburn 3193: my %personnel = ();
1.841 albertel 3194:
3195: my %servers = &get_servers($dom,'library');
3196: foreach my $tryserver (keys(%servers)) {
3197: %{$personnel{$tryserver}}=();
3198: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3199: &escape($startdate).':'.
3200: &escape($enddate).':'.
3201: &escape($rolelist), $tryserver))) {
3202: my ($key,$value) = split(/\=/,$line,2);
3203: if (($key) && ($value)) {
3204: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3205: }
3206: }
1.662 raeburn 3207: }
3208: return %personnel;
3209: }
1.658 raeburn 3210:
1.149 www 3211: # ----------------------------------------------------------- Check out an item
3212:
1.504 albertel 3213: sub get_first_access {
3214: my ($type,$argsymb)=@_;
1.790 albertel 3215: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3216: if ($argsymb) { $symb=$argsymb; }
3217: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3218: if ($type eq 'course') {
3219: $res='course';
3220: } elsif ($type eq 'map') {
1.588 albertel 3221: $res=&symbread($map);
3222: } else {
3223: $res=$symb;
3224: }
3225: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3226: return $times{"$courseid\0$res"};
1.504 albertel 3227: }
3228:
3229: sub set_first_access {
3230: my ($type)=@_;
1.790 albertel 3231: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3232: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3233: if ($type eq 'course') {
3234: $res='course';
3235: } elsif ($type eq 'map') {
1.588 albertel 3236: $res=&symbread($map);
3237: } else {
3238: $res=$symb;
3239: }
3240: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3241: if (!$firstaccess) {
1.588 albertel 3242: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3243: }
3244: return 'already_set';
1.504 albertel 3245: }
3246:
1.149 www 3247: sub checkout {
3248: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3249: my $now=time;
3250: my $lonhost=$perlvar{'lonHostID'};
3251: my $infostr=&escape(
1.234 www 3252: 'CHECKOUTTOKEN&'.
1.149 www 3253: $tuname.'&'.
3254: $tudom.'&'.
3255: $tcrsid.'&'.
3256: $symb.'&'.
3257: $now.'&'.$ENV{'REMOTE_ADDR'});
3258: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3259: if ($token=~/^error\:/) {
1.672 albertel 3260: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3261: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3262: "</font>");
3263: return '';
3264: }
3265:
1.149 www 3266: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3267: $token=~tr/a-z/A-Z/;
3268:
1.153 www 3269: my %infohash=('resource.0.outtoken' => $token,
3270: 'resource.0.checkouttime' => $now,
3271: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3272:
3273: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3274: return '';
1.151 www 3275: } else {
1.672 albertel 3276: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3277: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3278: "</font>");
1.149 www 3279: }
3280:
3281: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3282: &escape('Checkout '.$infostr.' - '.
3283: $token)) ne 'ok') {
3284: return '';
1.151 www 3285: } else {
1.672 albertel 3286: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3287: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3288: "</font>");
1.149 www 3289: }
1.151 www 3290: return $token;
1.149 www 3291: }
3292:
3293: # ------------------------------------------------------------ Check in an item
3294:
3295: sub checkin {
3296: my $token=shift;
1.150 www 3297: my $now=time;
3298: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3299: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3300: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3301: $dtoken=~s/\W/\_/g;
1.234 www 3302: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3303: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3304:
1.154 www 3305: unless (($tuname) && ($tudom)) {
3306: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3307: return '';
3308: }
3309:
3310: unless (&allowed('mgr',$tcrsid)) {
3311: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3312: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3313: return '';
3314: }
3315:
1.153 www 3316: my %infohash=('resource.0.intoken' => $token,
3317: 'resource.0.checkintime' => $now,
3318: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3319:
3320: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3321: return '';
3322: }
3323:
3324: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3325: &escape('Checkin - '.$token)) ne 'ok') {
3326: return '';
3327: }
3328:
3329: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3330: }
3331:
3332: # --------------------------------------------- Set Expire Date for Spreadsheet
3333:
3334: sub expirespread {
3335: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3336: my $cid=$env{'request.course.id'};
1.110 www 3337: if ($cid) {
3338: my $now=time;
3339: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3340: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3341: $env{'course.'.$cid.'.num'}.
1.110 www 3342: ':nohist_expirationdates:'.
3343: &escape($key).'='.$now,
1.620 albertel 3344: $env{'course.'.$cid.'.home'})
1.110 www 3345: }
3346: return 'ok';
1.14 www 3347: }
3348:
1.109 www 3349: # ----------------------------------------------------- Devalidate Spreadsheets
3350:
3351: sub devalidate {
1.325 www 3352: my ($symb,$uname,$udom)=@_;
1.620 albertel 3353: my $cid=$env{'request.course.id'};
1.109 www 3354: if ($cid) {
1.391 matthew 3355: # delete the stored spreadsheets for
3356: # - the student level sheet of this user in course's homespace
3357: # - the assessment level sheet for this resource
3358: # for this user in user's homespace
1.553 albertel 3359: # - current conditional state info
1.325 www 3360: my $key=$uname.':'.$udom.':';
1.109 www 3361: my $status=
1.299 matthew 3362: &del('nohist_calculatedsheets',
1.391 matthew 3363: [$key.'studentcalc:'],
1.620 albertel 3364: $env{'course.'.$cid.'.domain'},
3365: $env{'course.'.$cid.'.num'})
1.133 albertel 3366: .' '.
3367: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3368: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3369: unless ($status eq 'ok ok') {
3370: &logthis('Could not devalidate spreadsheet '.
1.325 www 3371: $uname.' at '.$udom.' for '.
1.109 www 3372: $symb.': '.$status);
1.133 albertel 3373: }
1.553 albertel 3374: &delenv('user.state.'.$cid);
1.109 www 3375: }
3376: }
3377:
1.265 albertel 3378: sub get_scalar {
3379: my ($string,$end) = @_;
3380: my $value;
3381: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3382: $value = $1;
3383: } elsif ($$string =~ s/^([^&]*?)&//) {
3384: $value = $1;
3385: }
3386: return &unescape($value);
3387: }
3388:
3389: sub array2str {
3390: my (@array) = @_;
3391: my $result=&arrayref2str(\@array);
3392: $result=~s/^__ARRAY_REF__//;
3393: $result=~s/__END_ARRAY_REF__$//;
3394: return $result;
3395: }
3396:
1.204 albertel 3397: sub arrayref2str {
3398: my ($arrayref) = @_;
1.265 albertel 3399: my $result='__ARRAY_REF__';
1.204 albertel 3400: foreach my $elem (@$arrayref) {
1.265 albertel 3401: if(ref($elem) eq 'ARRAY') {
3402: $result.=&arrayref2str($elem).'&';
3403: } elsif(ref($elem) eq 'HASH') {
3404: $result.=&hashref2str($elem).'&';
3405: } elsif(ref($elem)) {
3406: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3407: } else {
3408: $result.=&escape($elem).'&';
3409: }
3410: }
3411: $result=~s/\&$//;
1.265 albertel 3412: $result .= '__END_ARRAY_REF__';
1.204 albertel 3413: return $result;
3414: }
3415:
1.168 albertel 3416: sub hash2str {
1.204 albertel 3417: my (%hash) = @_;
3418: my $result=&hashref2str(\%hash);
1.265 albertel 3419: $result=~s/^__HASH_REF__//;
3420: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3421: return $result;
3422: }
3423:
3424: sub hashref2str {
3425: my ($hashref)=@_;
1.265 albertel 3426: my $result='__HASH_REF__';
1.800 albertel 3427: foreach my $key (sort(keys(%$hashref))) {
3428: if (ref($key) eq 'ARRAY') {
3429: $result.=&arrayref2str($key).'=';
3430: } elsif (ref($key) eq 'HASH') {
3431: $result.=&hashref2str($key).'=';
3432: } elsif (ref($key)) {
1.265 albertel 3433: $result.='=';
1.800 albertel 3434: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3435: } else {
1.800 albertel 3436: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3437: }
3438:
1.800 albertel 3439: if(ref($hashref->{$key}) eq 'ARRAY') {
3440: $result.=&arrayref2str($hashref->{$key}).'&';
3441: } elsif(ref($hashref->{$key}) eq 'HASH') {
3442: $result.=&hashref2str($hashref->{$key}).'&';
3443: } elsif(ref($hashref->{$key})) {
1.265 albertel 3444: $result.='&';
1.800 albertel 3445: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3446: } else {
1.800 albertel 3447: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3448: }
3449: }
1.168 albertel 3450: $result=~s/\&$//;
1.265 albertel 3451: $result .= '__END_HASH_REF__';
1.168 albertel 3452: return $result;
3453: }
3454:
3455: sub str2hash {
1.265 albertel 3456: my ($string)=@_;
3457: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3458: return %$hash;
3459: }
3460:
3461: sub str2hashref {
1.168 albertel 3462: my ($string) = @_;
1.265 albertel 3463:
3464: my %hash;
3465:
3466: if($string !~ /^__HASH_REF__/) {
3467: if (! ($string eq '' || !defined($string))) {
3468: $hash{'error'}='Not hash reference';
3469: }
3470: return (\%hash, $string);
3471: }
3472:
3473: $string =~ s/^__HASH_REF__//;
3474:
3475: while($string !~ /^__END_HASH_REF__/) {
3476: #key
3477: my $key='';
3478: if($string =~ /^__HASH_REF__/) {
3479: ($key, $string)=&str2hashref($string);
3480: if(defined($key->{'error'})) {
3481: $hash{'error'}='Bad data';
3482: return (\%hash, $string);
3483: }
3484: } elsif($string =~ /^__ARRAY_REF__/) {
3485: ($key, $string)=&str2arrayref($string);
3486: if($key->[0] eq 'Array reference error') {
3487: $hash{'error'}='Bad data';
3488: return (\%hash, $string);
3489: }
3490: } else {
3491: $string =~ s/^(.*?)=//;
1.267 albertel 3492: $key=&unescape($1);
1.265 albertel 3493: }
3494: $string =~ s/^=//;
3495:
3496: #value
3497: my $value='';
3498: if($string =~ /^__HASH_REF__/) {
3499: ($value, $string)=&str2hashref($string);
3500: if(defined($value->{'error'})) {
3501: $hash{'error'}='Bad data';
3502: return (\%hash, $string);
3503: }
3504: } elsif($string =~ /^__ARRAY_REF__/) {
3505: ($value, $string)=&str2arrayref($string);
3506: if($value->[0] eq 'Array reference error') {
3507: $hash{'error'}='Bad data';
3508: return (\%hash, $string);
3509: }
3510: } else {
3511: $value=&get_scalar(\$string,'__END_HASH_REF__');
3512: }
3513: $string =~ s/^&//;
3514:
3515: $hash{$key}=$value;
1.204 albertel 3516: }
1.265 albertel 3517:
3518: $string =~ s/^__END_HASH_REF__//;
3519:
3520: return (\%hash, $string);
1.204 albertel 3521: }
3522:
3523: sub str2array {
1.265 albertel 3524: my ($string)=@_;
3525: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3526: return @$array;
3527: }
3528:
3529: sub str2arrayref {
1.204 albertel 3530: my ($string) = @_;
1.265 albertel 3531: my @array;
3532:
3533: if($string !~ /^__ARRAY_REF__/) {
3534: if (! ($string eq '' || !defined($string))) {
3535: $array[0]='Array reference error';
3536: }
3537: return (\@array, $string);
3538: }
3539:
3540: $string =~ s/^__ARRAY_REF__//;
3541:
3542: while($string !~ /^__END_ARRAY_REF__/) {
3543: my $value='';
3544: if($string =~ /^__HASH_REF__/) {
3545: ($value, $string)=&str2hashref($string);
3546: if(defined($value->{'error'})) {
3547: $array[0] ='Array reference error';
3548: return (\@array, $string);
3549: }
3550: } elsif($string =~ /^__ARRAY_REF__/) {
3551: ($value, $string)=&str2arrayref($string);
3552: if($value->[0] eq 'Array reference error') {
3553: $array[0] ='Array reference error';
3554: return (\@array, $string);
3555: }
3556: } else {
3557: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3558: }
3559: $string =~ s/^&//;
3560:
3561: push(@array, $value);
1.191 harris41 3562: }
1.265 albertel 3563:
3564: $string =~ s/^__END_ARRAY_REF__//;
3565:
3566: return (\@array, $string);
1.168 albertel 3567: }
3568:
1.167 albertel 3569: # -------------------------------------------------------------------Temp Store
3570:
1.168 albertel 3571: sub tmpreset {
3572: my ($symb,$namespace,$domain,$stuname) = @_;
3573: if (!$symb) {
3574: $symb=&symbread();
1.620 albertel 3575: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3576: }
3577: $symb=escape($symb);
3578:
1.620 albertel 3579: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3580: $namespace=~s/\//\_/g;
3581: $namespace=~s/\W//g;
3582:
1.620 albertel 3583: if (!$domain) { $domain=$env{'user.domain'}; }
3584: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3585: if ($domain eq 'public' && $stuname eq 'public') {
3586: $stuname=$ENV{'REMOTE_ADDR'};
3587: }
1.168 albertel 3588: my $path=$perlvar{'lonDaemons'}.'/tmp';
3589: my %hash;
3590: if (tie(%hash,'GDBM_File',
3591: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3592: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3593: foreach my $key (keys(%hash)) {
1.180 albertel 3594: if ($key=~ /:$symb/) {
1.168 albertel 3595: delete($hash{$key});
3596: }
3597: }
3598: }
3599: }
3600:
1.167 albertel 3601: sub tmpstore {
1.168 albertel 3602: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3603:
3604: if (!$symb) {
3605: $symb=&symbread();
1.620 albertel 3606: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3607: }
3608: $symb=escape($symb);
3609:
3610: if (!$namespace) {
3611: # I don't think we would ever want to store this for a course.
3612: # it seems this will only be used if we don't have a course.
1.620 albertel 3613: #$namespace=$env{'request.course.id'};
1.168 albertel 3614: #if (!$namespace) {
1.620 albertel 3615: $namespace=$env{'request.state'};
1.168 albertel 3616: #}
3617: }
3618: $namespace=~s/\//\_/g;
3619: $namespace=~s/\W//g;
1.620 albertel 3620: if (!$domain) { $domain=$env{'user.domain'}; }
3621: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3622: if ($domain eq 'public' && $stuname eq 'public') {
3623: $stuname=$ENV{'REMOTE_ADDR'};
3624: }
1.168 albertel 3625: my $now=time;
3626: my %hash;
3627: my $path=$perlvar{'lonDaemons'}.'/tmp';
3628: if (tie(%hash,'GDBM_File',
3629: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3630: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3631: $hash{"version:$symb"}++;
3632: my $version=$hash{"version:$symb"};
3633: my $allkeys='';
3634: foreach my $key (keys(%$storehash)) {
3635: $allkeys.=$key.':';
1.591 albertel 3636: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3637: }
3638: $hash{"$version:$symb:timestamp"}=$now;
3639: $allkeys.='timestamp';
3640: $hash{"$version:keys:$symb"}=$allkeys;
3641: if (untie(%hash)) {
3642: return 'ok';
3643: } else {
3644: return "error:$!";
3645: }
3646: } else {
3647: return "error:$!";
3648: }
3649: }
1.167 albertel 3650:
1.168 albertel 3651: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3652:
1.168 albertel 3653: sub tmprestore {
3654: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3655:
1.168 albertel 3656: if (!$symb) {
3657: $symb=&symbread();
1.620 albertel 3658: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3659: }
3660: $symb=escape($symb);
3661:
1.620 albertel 3662: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3663:
1.620 albertel 3664: if (!$domain) { $domain=$env{'user.domain'}; }
3665: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3666: if ($domain eq 'public' && $stuname eq 'public') {
3667: $stuname=$ENV{'REMOTE_ADDR'};
3668: }
1.168 albertel 3669: my %returnhash;
3670: $namespace=~s/\//\_/g;
3671: $namespace=~s/\W//g;
3672: my %hash;
3673: my $path=$perlvar{'lonDaemons'}.'/tmp';
3674: if (tie(%hash,'GDBM_File',
3675: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3676: &GDBM_READER(),0640)) {
1.168 albertel 3677: my $version=$hash{"version:$symb"};
3678: $returnhash{'version'}=$version;
3679: my $scope;
3680: for ($scope=1;$scope<=$version;$scope++) {
3681: my $vkeys=$hash{"$scope:keys:$symb"};
3682: my @keys=split(/:/,$vkeys);
3683: my $key;
3684: $returnhash{"$scope:keys"}=$vkeys;
3685: foreach $key (@keys) {
1.591 albertel 3686: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3687: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3688: }
3689: }
1.168 albertel 3690: if (!(untie(%hash))) {
3691: return "error:$!";
3692: }
3693: } else {
3694: return "error:$!";
3695: }
3696: return %returnhash;
1.167 albertel 3697: }
3698:
1.9 www 3699: # ----------------------------------------------------------------------- Store
3700:
3701: sub store {
1.124 www 3702: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3703: my $home='';
3704:
1.168 albertel 3705: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3706:
1.213 www 3707: $symb=&symbclean($symb);
1.122 albertel 3708: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3709:
1.620 albertel 3710: if (!$domain) { $domain=$env{'user.domain'}; }
3711: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3712:
3713: &devalidate($symb,$stuname,$domain);
1.109 www 3714:
3715: $symb=escape($symb);
1.187 www 3716: if (!$namespace) {
1.620 albertel 3717: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3718: return '';
3719: }
3720: }
1.620 albertel 3721: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3722:
3723: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3724: $$storehash{'host'}=$perlvar{'lonHostID'};
3725:
1.12 www 3726: my $namevalue='';
1.800 albertel 3727: foreach my $key (keys(%$storehash)) {
3728: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3729: }
1.12 www 3730: $namevalue=~s/\&$//;
1.187 www 3731: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3732: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3733: }
3734:
1.47 www 3735: # -------------------------------------------------------------- Critical Store
3736:
3737: sub cstore {
1.124 www 3738: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3739: my $home='';
3740:
1.168 albertel 3741: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3742:
1.213 www 3743: $symb=&symbclean($symb);
1.122 albertel 3744: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3745:
1.620 albertel 3746: if (!$domain) { $domain=$env{'user.domain'}; }
3747: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3748:
3749: &devalidate($symb,$stuname,$domain);
1.109 www 3750:
3751: $symb=escape($symb);
1.187 www 3752: if (!$namespace) {
1.620 albertel 3753: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3754: return '';
3755: }
3756: }
1.620 albertel 3757: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3758:
3759: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3760: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3761:
1.47 www 3762: my $namevalue='';
1.800 albertel 3763: foreach my $key (keys(%$storehash)) {
3764: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3765: }
1.47 www 3766: $namevalue=~s/\&$//;
1.187 www 3767: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3768: return critical
3769: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3770: }
3771:
1.9 www 3772: # --------------------------------------------------------------------- Restore
3773:
3774: sub restore {
1.124 www 3775: my ($symb,$namespace,$domain,$stuname) = @_;
3776: my $home='';
3777:
1.168 albertel 3778: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3779:
1.122 albertel 3780: if (!$symb) {
3781: unless ($symb=escape(&symbread())) { return ''; }
3782: } else {
1.213 www 3783: $symb=&escape(&symbclean($symb));
1.122 albertel 3784: }
1.188 www 3785: if (!$namespace) {
1.620 albertel 3786: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3787: return '';
3788: }
3789: }
1.620 albertel 3790: if (!$domain) { $domain=$env{'user.domain'}; }
3791: if (!$stuname) { $stuname=$env{'user.name'}; }
3792: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3793: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3794:
1.12 www 3795: my %returnhash=();
1.800 albertel 3796: foreach my $line (split(/\&/,$answer)) {
3797: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3798: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3799: }
1.75 www 3800: my $version;
3801: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3802: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3803: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3804: }
1.75 www 3805: }
1.13 www 3806: return %returnhash;
1.34 www 3807: }
3808:
3809: # ---------------------------------------------------------- Course Description
3810:
3811: sub coursedescription {
1.731 albertel 3812: my ($courseid,$args)=@_;
1.34 www 3813: $courseid=~s/^\///;
1.49 www 3814: $courseid=~s/\_/\//g;
1.34 www 3815: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3816: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3817: my $normalid=$cdomain.'_'.$cnum;
3818: # need to always cache even if we get errors otherwise we keep
3819: # trying and trying and trying to get the course description.
3820: my %envhash=();
3821: my %returnhash=();
1.731 albertel 3822:
3823: my $expiretime=600;
3824: if ($env{'request.course.id'} eq $normalid) {
3825: $expiretime=120;
3826: }
3827:
3828: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3829: if (!$args->{'freshen_cache'}
3830: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3831: foreach my $key (keys(%env)) {
3832: next if ($key !~ /^\Q$prefix\E(.*)/);
3833: my ($setting) = $1;
3834: $returnhash{$setting} = $env{$key};
3835: }
3836: return %returnhash;
3837: }
3838:
3839: # get the data agin
3840: if (!$args->{'one_time'}) {
3841: $envhash{'course.'.$normalid.'.last_cache'}=time;
3842: }
1.811 albertel 3843:
1.34 www 3844: if ($chome ne 'no_host') {
1.302 albertel 3845: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3846: if (!exists($returnhash{'con_lost'})) {
3847: $returnhash{'home'}= $chome;
3848: $returnhash{'domain'} = $cdomain;
3849: $returnhash{'num'} = $cnum;
1.741 raeburn 3850: if (!defined($returnhash{'type'})) {
3851: $returnhash{'type'} = 'Course';
3852: }
1.130 albertel 3853: while (my ($name,$value) = each %returnhash) {
1.53 www 3854: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3855: }
1.270 www 3856: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3857: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3858: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3859: $envhash{'course.'.$normalid.'.home'}=$chome;
3860: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3861: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3862: }
3863: }
1.731 albertel 3864: if (!$args->{'one_time'}) {
1.949 raeburn 3865: &appenv(\%envhash);
1.731 albertel 3866: }
1.302 albertel 3867: return %returnhash;
1.461 www 3868: }
3869:
3870: # -------------------------------------------------See if a user is privileged
3871:
3872: sub privileged {
3873: my ($username,$domain)=@_;
3874: my $rolesdump=&reply("dump:$domain:$username:roles",
3875: &homeserver($username,$domain));
1.1033 raeburn 3876: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3877: ($rolesdump =~ /^error:/)) {
3878: return 0;
3879: }
1.461 www 3880: my $now=time;
3881: if ($rolesdump ne '') {
1.800 albertel 3882: foreach my $entry (split(/&/,$rolesdump)) {
3883: if ($entry!~/^rolesdef_/) {
3884: my ($area,$role)=split(/=/,$entry);
1.461 www 3885: $area=~s/\_\w\w$//;
3886: my ($trole,$tend,$tstart)=split(/_/,$role);
3887: if (($trole eq 'dc') || ($trole eq 'su')) {
3888: my $active=1;
3889: if ($tend) {
3890: if ($tend<$now) { $active=0; }
3891: }
3892: if ($tstart) {
3893: if ($tstart>$now) { $active=0; }
3894: }
3895: if ($active) { return 1; }
3896: }
3897: }
3898: }
3899: }
3900: return 0;
1.9 www 3901: }
1.1 albertel 3902:
1.103 harris41 3903: # -------------------------------------------------------- Get user privileges
1.11 www 3904:
3905: sub rolesinit {
3906: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3907: my $now=time;
3908: my %userroles = ('user.login.time' => $now);
1.11 www 3909: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 3910: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3911: ($rolesdump =~ /^error:/)) {
3912: return \%userroles;
3913: }
1.11 www 3914: my %allroles=();
1.678 raeburn 3915: my %allgroups=();
3916: my $group_privs;
1.11 www 3917:
3918: if ($rolesdump ne '') {
1.800 albertel 3919: foreach my $entry (split(/&/,$rolesdump)) {
3920: if ($entry!~/^rolesdef_/) {
3921: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3922: $area=~s/\_\w\w$//;
1.678 raeburn 3923: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3924: if ($role=~/^cr/) {
1.807 albertel 3925: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3926: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3927: ($tend,$tstart)=split('_',$trest);
3928: } else {
3929: $trole=$role;
3930: }
1.678 raeburn 3931: } elsif ($role =~ m|^gr/|) {
3932: ($trole,$tend,$tstart) = split(/_/,$role);
3933: ($trole,$group_privs) = split(/\//,$trole);
3934: $group_privs = &unescape($group_privs);
1.587 albertel 3935: } else {
3936: ($trole,$tend,$tstart)=split(/_/,$role);
3937: }
1.743 albertel 3938: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3939: $username);
3940: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3941: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3942: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3943: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3944: my $spec=$trole.'.'.$area;
3945: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3946: if ($trole =~ /^cr\//) {
1.567 raeburn 3947: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3948: } elsif ($trole eq 'gr') {
3949: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3950: } else {
1.567 raeburn 3951: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3952: }
1.12 www 3953: }
1.662 raeburn 3954: }
1.191 harris41 3955: }
1.743 albertel 3956: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3957: $userroles{'user.adv'} = $adv;
3958: $userroles{'user.author'} = $author;
1.620 albertel 3959: $env{'user.adv'}=$adv;
1.11 www 3960: }
1.743 albertel 3961: return \%userroles;
1.11 www 3962: }
3963:
1.567 raeburn 3964: sub set_arearole {
3965: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3966: # log the associated role with the area
3967: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3968: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3969: }
3970:
3971: sub custom_roleprivs {
3972: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3973: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3974: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3975: if (&hostname($homsvr) ne '') {
1.567 raeburn 3976: my ($rdummy,$roledef)=
3977: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3978: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3979: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3980: if (defined($syspriv)) {
1.1043 raeburn 3981: if ($trest =~ /^$match_community$/) {
3982: $syspriv =~ s/bre\&S//;
3983: }
1.567 raeburn 3984: $$allroles{'cm./'}.=':'.$syspriv;
3985: $$allroles{$spec.'./'}.=':'.$syspriv;
3986: }
3987: if ($tdomain ne '') {
3988: if (defined($dompriv)) {
3989: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3990: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3991: }
3992: if (($trest ne '') && (defined($coursepriv))) {
3993: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3994: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3995: }
3996: }
3997: }
3998: }
3999: }
4000:
1.678 raeburn 4001: sub group_roleprivs {
4002: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4003: my $access = 1;
4004: my $now = time;
4005: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4006: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4007: if ($access) {
1.811 albertel 4008: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4009: $$allgroups{$course}{$group} .=':'.$group_privs;
4010: }
4011: }
1.567 raeburn 4012:
4013: sub standard_roleprivs {
4014: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4015: if (defined($pr{$trole.':s'})) {
4016: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4017: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4018: }
4019: if ($tdomain ne '') {
4020: if (defined($pr{$trole.':d'})) {
4021: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4022: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4023: }
4024: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4025: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4026: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4027: }
4028: }
4029: }
4030:
4031: sub set_userprivs {
1.1056.2.3 raeburn 4032: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4033: my $author=0;
4034: my $adv=0;
1.678 raeburn 4035: my %grouproles = ();
4036: if (keys(%{$allgroups}) > 0) {
1.1056.2.3 raeburn 4037: my @groupkeys;
1.1000 raeburn 4038: foreach my $role (keys(%{$allroles})) {
1.1056.2.3 raeburn 4039: push(@groupkeys,$role);
4040: }
4041: if (ref($groups_roles) eq 'HASH') {
4042: foreach my $key (keys(%{$groups_roles})) {
4043: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4044: push(@groupkeys,$key);
4045: }
4046: }
4047: }
4048: if (@groupkeys > 0) {
4049: foreach my $role (@groupkeys) {
4050: my ($trole,$area,$sec,$extendedarea);
4051: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4052: $trole = $1;
4053: $area = $2;
4054: $sec = $3;
4055: $extendedarea = $area.$sec;
4056: if (exists($$allgroups{$area})) {
4057: foreach my $group (keys(%{$$allgroups{$area}})) {
4058: my $spec = $trole.'.'.$extendedarea;
4059: $grouproles{$spec.'.'.$area.'/'.$group} =
4060: $$allgroups{$area}{$group};
4061: }
1.678 raeburn 4062: }
4063: }
4064: }
4065: }
4066: }
1.800 albertel 4067: foreach my $group (keys(%grouproles)) {
4068: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4069: }
1.800 albertel 4070: foreach my $role (keys(%{$allroles})) {
4071: my %thesepriv;
1.941 raeburn 4072: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4073: foreach my $item (split(/:/,$$allroles{$role})) {
4074: if ($item ne '') {
4075: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4076: if ($restrictions eq '') {
4077: $thesepriv{$privilege}='F';
4078: } elsif ($thesepriv{$privilege} ne 'F') {
4079: $thesepriv{$privilege}.=$restrictions;
4080: }
4081: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4082: }
4083: }
4084: my $thesestr='';
1.800 albertel 4085: foreach my $priv (keys(%thesepriv)) {
4086: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4087: }
4088: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4089: }
4090: return ($author,$adv);
4091: }
4092:
1.994 raeburn 4093: sub role_status {
1.1002 raeburn 4094: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4095: my @pwhere = ();
4096: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4097: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4098: unless (!defined($$role) || $$role eq '') {
4099: $$where=join('.',@pwhere);
4100: $$trolecode=$$role.'.'.$$where;
4101: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4102: $$tstatus='is';
4103: if ($$tstart && $$tstart>$then) {
4104: $$tstatus='future';
1.1034 raeburn 4105: if ($$tstart<$now) {
4106: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4107: if (($$where ne '') && ($$role ne '')) {
1.1056.2.3 raeburn 4108: my (%allroles,%allgroups,$group_privs,
4109: %groups_roles,@rolecodes);
1.1002 raeburn 4110: my %userroles = (
4111: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4112: );
1.1056.2.3 raeburn 4113: @rolecodes = ('cm');
1.1002 raeburn 4114: my $spec=$$role.'.'.$$where;
4115: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4116: if ($$role =~ /^cr\//) {
4117: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.2.3 raeburn 4118: push(@rolecodes,'cr');
1.1002 raeburn 4119: } elsif ($$role eq 'gr') {
1.1056.2.3 raeburn 4120: push(@rolecodes,$$role);
1.1002 raeburn 4121: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4122: $env{'user.name'});
1.1056.2.3 raeburn 4123: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4124: (undef,my $group_privs) = split(/\//,$trole);
4125: $group_privs = &unescape($group_privs);
4126: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.2.3 raeburn 4127: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4128: if (keys(%course_roles) > 0) {
4129: my ($tnum) = ($trest =~ /^($match_courseid)/);
4130: if ($tdomain ne '' && $tnum ne '') {
4131: foreach my $key (keys(%course_roles)) {
4132: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4133: my $crsrole = $1;
4134: my $crssec = $2;
4135: if ($crsrole =~ /^cr/) {
4136: unless (grep(/^cr$/,@rolecodes)) {
4137: push(@rolecodes,'cr');
4138: }
4139: } else {
4140: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4141: push(@rolecodes,$crsrole);
4142: }
4143: }
4144: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4145: if ($crssec ne '') {
4146: $rolekey .= '/'.$crssec;
4147: }
4148: $rolekey .= './';
4149: $groups_roles{$rolekey} = \@rolecodes;
4150: }
4151: }
4152: }
4153: }
1.1002 raeburn 4154: } else {
1.1056.2.3 raeburn 4155: push(@rolecodes,$$role);
1.1002 raeburn 4156: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4157: }
1.1056.2.3 raeburn 4158: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4159: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4160: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4161: }
4162: }
1.1034 raeburn 4163: $$tstatus = 'is';
1.1002 raeburn 4164: }
1.994 raeburn 4165: }
4166: if ($$tend) {
4167: if ($$tend<$then) {
4168: $$tstatus='expired';
4169: } elsif ($$tend<$now) {
4170: $$tstatus='will_not';
4171: }
4172: }
4173: }
4174: }
4175: }
4176:
4177: sub check_adhoc_privs {
1.1056.2.8! raeburn 4178: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4179: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4180: if ($env{$cckey}) {
4181: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4182: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4183: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.2.8! raeburn 4184: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4185: }
4186: } else {
1.1056.2.8! raeburn 4187: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4188: }
4189: }
4190:
4191: sub set_adhoc_privileges {
4192: # role can be cc or ca
1.1056.2.8! raeburn 4193: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4194: my $area = '/'.$dcdom.'/'.$pickedcourse;
4195: my $spec = $role.'.'.$area;
4196: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4197: $env{'user.name'});
4198: my %ccrole = ();
4199: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4200: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4201: &appenv(\%userroles,[$role,'cm']);
4202: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.2.8! raeburn 4203: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
! 4204: &appenv( {'request.role' => $spec,
! 4205: 'request.role.domain' => $dcdom,
! 4206: 'request.course.sec' => ''
! 4207: }
! 4208: );
! 4209: my $tadv=0;
! 4210: if (&allowed('adv') eq 'F') { $tadv=1; }
! 4211: &appenv({'request.role.adv' => $tadv});
! 4212: }
1.994 raeburn 4213: }
4214:
1.12 www 4215: # --------------------------------------------------------------- get interface
4216:
4217: sub get {
1.131 albertel 4218: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4219: my $items='';
1.800 albertel 4220: foreach my $item (@$storearr) {
4221: $items.=&escape($item).'&';
1.191 harris41 4222: }
1.12 www 4223: $items=~s/\&$//;
1.620 albertel 4224: if (!$udomain) { $udomain=$env{'user.domain'}; }
4225: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4226: my $uhome=&homeserver($uname,$udomain);
4227:
1.133 albertel 4228: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4229: my @pairs=split(/\&/,$rep);
1.273 albertel 4230: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4231: return @pairs;
4232: }
1.15 www 4233: my %returnhash=();
1.42 www 4234: my $i=0;
1.800 albertel 4235: foreach my $item (@$storearr) {
4236: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4237: $i++;
1.191 harris41 4238: }
1.15 www 4239: return %returnhash;
1.27 www 4240: }
4241:
4242: # --------------------------------------------------------------- del interface
4243:
4244: sub del {
1.133 albertel 4245: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4246: my $items='';
1.800 albertel 4247: foreach my $item (@$storearr) {
4248: $items.=&escape($item).'&';
1.191 harris41 4249: }
1.984 neumanie 4250:
1.27 www 4251: $items=~s/\&$//;
1.620 albertel 4252: if (!$udomain) { $udomain=$env{'user.domain'}; }
4253: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4254: my $uhome=&homeserver($uname,$udomain);
4255: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4256: }
4257:
4258: # -------------------------------------------------------------- dump interface
4259:
4260: sub dump {
1.755 albertel 4261: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4262: if (!$udomain) { $udomain=$env{'user.domain'}; }
4263: if (!$uname) { $uname=$env{'user.name'}; }
4264: my $uhome=&homeserver($uname,$udomain);
4265: if ($regexp) {
4266: $regexp=&escape($regexp);
4267: } else {
4268: $regexp='.';
4269: }
4270: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4271: my @pairs=split(/\&/,$rep);
4272: my %returnhash=();
4273: foreach my $item (@pairs) {
4274: my ($key,$value)=split(/=/,$item,2);
4275: $key = &unescape($key);
4276: next if ($key =~ /^error: 2 /);
4277: $returnhash{$key}=&thaw_unescape($value);
4278: }
4279: return %returnhash;
1.407 www 4280: }
4281:
1.717 albertel 4282: # --------------------------------------------------------- dumpstore interface
4283:
4284: sub dumpstore {
4285: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4286: if (!$udomain) { $udomain=$env{'user.domain'}; }
4287: if (!$uname) { $uname=$env{'user.name'}; }
4288: my $uhome=&homeserver($uname,$udomain);
4289: if ($regexp) {
4290: $regexp=&escape($regexp);
4291: } else {
4292: $regexp='.';
4293: }
4294: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4295: my @pairs=split(/\&/,$rep);
4296: my %returnhash=();
4297: foreach my $item (@pairs) {
4298: my ($key,$value)=split(/=/,$item,2);
4299: next if ($key =~ /^error: 2 /);
4300: $returnhash{$key}=&thaw_unescape($value);
4301: }
4302: return %returnhash;
1.717 albertel 4303: }
4304:
1.407 www 4305: # -------------------------------------------------------------- keys interface
4306:
4307: sub getkeys {
4308: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4309: if (!$udomain) { $udomain=$env{'user.domain'}; }
4310: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4311: my $uhome=&homeserver($uname,$udomain);
4312: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4313: my @keyarray=();
1.800 albertel 4314: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4315: next if ($key =~ /^error: 2 /);
1.800 albertel 4316: push(@keyarray,&unescape($key));
1.407 www 4317: }
4318: return @keyarray;
1.318 matthew 4319: }
4320:
1.319 matthew 4321: # --------------------------------------------------------------- currentdump
4322: sub currentdump {
1.328 matthew 4323: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4324: $courseid = $env{'request.course.id'} if (! defined($courseid));
4325: $sdom = $env{'user.domain'} if (! defined($sdom));
4326: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4327: my $uhome = &homeserver($sname,$sdom);
4328: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4329: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4330: #
1.318 matthew 4331: my %returnhash=();
1.319 matthew 4332: #
4333: if ($rep eq "unknown_cmd") {
4334: # an old lond will not know currentdump
4335: # Do a dump and make it look like a currentdump
1.822 albertel 4336: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4337: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4338: my %hash = @tmp;
4339: @tmp=();
1.424 matthew 4340: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4341: } else {
4342: my @pairs=split(/\&/,$rep);
1.800 albertel 4343: foreach my $pair (@pairs) {
4344: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4345: my ($symb,$param) = split(/:/,$key);
4346: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4347: &thaw_unescape($value);
1.319 matthew 4348: }
1.191 harris41 4349: }
1.12 www 4350: return %returnhash;
1.424 matthew 4351: }
4352:
4353: sub convert_dump_to_currentdump{
4354: my %hash = %{shift()};
4355: my %returnhash;
4356: # Code ripped from lond, essentially. The only difference
4357: # here is the unescaping done by lonnet::dump(). Conceivably
4358: # we might run in to problems with parameter names =~ /^v\./
4359: while (my ($key,$value) = each(%hash)) {
4360: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4361: $symb = &unescape($symb);
4362: $param = &unescape($param);
1.424 matthew 4363: next if ($v eq 'version' || $symb eq 'keys');
4364: next if (exists($returnhash{$symb}) &&
4365: exists($returnhash{$symb}->{$param}) &&
4366: $returnhash{$symb}->{'v.'.$param} > $v);
4367: $returnhash{$symb}->{$param}=$value;
4368: $returnhash{$symb}->{'v.'.$param}=$v;
4369: }
4370: #
4371: # Remove all of the keys in the hashes which keep track of
4372: # the version of the parameter.
4373: while (my ($symb,$param_hash) = each(%returnhash)) {
4374: # use a foreach because we are going to delete from the hash.
4375: foreach my $key (keys(%$param_hash)) {
4376: delete($param_hash->{$key}) if ($key =~ /^v\./);
4377: }
4378: }
4379: return \%returnhash;
1.12 www 4380: }
4381:
1.627 albertel 4382: # ------------------------------------------------------ critical inc interface
4383:
4384: sub cinc {
4385: return &inc(@_,'critical');
4386: }
4387:
1.449 matthew 4388: # --------------------------------------------------------------- inc interface
4389:
4390: sub inc {
1.627 albertel 4391: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4392: if (!$udomain) { $udomain=$env{'user.domain'}; }
4393: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4394: my $uhome=&homeserver($uname,$udomain);
4395: my $items='';
4396: if (! ref($store)) {
4397: # got a single value, so use that instead
4398: $items = &escape($store).'=&';
4399: } elsif (ref($store) eq 'SCALAR') {
4400: $items = &escape($$store).'=&';
4401: } elsif (ref($store) eq 'ARRAY') {
4402: $items = join('=&',map {&escape($_);} @{$store});
4403: } elsif (ref($store) eq 'HASH') {
4404: while (my($key,$value) = each(%{$store})) {
4405: $items.= &escape($key).'='.&escape($value).'&';
4406: }
4407: }
4408: $items=~s/\&$//;
1.627 albertel 4409: if ($critical) {
4410: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4411: } else {
4412: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4413: }
1.449 matthew 4414: }
4415:
1.12 www 4416: # --------------------------------------------------------------- put interface
4417:
4418: sub put {
1.134 albertel 4419: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4420: if (!$udomain) { $udomain=$env{'user.domain'}; }
4421: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4422: my $uhome=&homeserver($uname,$udomain);
1.12 www 4423: my $items='';
1.800 albertel 4424: foreach my $item (keys(%$storehash)) {
4425: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4426: }
1.12 www 4427: $items=~s/\&$//;
1.134 albertel 4428: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4429: }
4430:
1.631 albertel 4431: # ------------------------------------------------------------ newput interface
4432:
4433: sub newput {
4434: my ($namespace,$storehash,$udomain,$uname)=@_;
4435: if (!$udomain) { $udomain=$env{'user.domain'}; }
4436: if (!$uname) { $uname=$env{'user.name'}; }
4437: my $uhome=&homeserver($uname,$udomain);
4438: my $items='';
4439: foreach my $key (keys(%$storehash)) {
4440: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4441: }
4442: $items=~s/\&$//;
4443: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4444: }
4445:
4446: # --------------------------------------------------------- putstore interface
4447:
1.524 raeburn 4448: sub putstore {
1.715 albertel 4449: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4450: if (!$udomain) { $udomain=$env{'user.domain'}; }
4451: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4452: my $uhome=&homeserver($uname,$udomain);
4453: my $items='';
1.715 albertel 4454: foreach my $key (keys(%$storehash)) {
4455: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4456: }
1.715 albertel 4457: $items=~s/\&$//;
1.716 albertel 4458: my $esc_symb=&escape($symb);
4459: my $esc_v=&escape($version);
1.715 albertel 4460: my $reply =
1.716 albertel 4461: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4462: $uhome);
4463: if ($reply eq 'unknown_cmd') {
1.716 albertel 4464: # gfall back to way things use to be done
1.715 albertel 4465: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4466: $uname);
1.524 raeburn 4467: }
1.715 albertel 4468: return $reply;
4469: }
4470:
4471: sub old_putstore {
1.716 albertel 4472: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4473: if (!$udomain) { $udomain=$env{'user.domain'}; }
4474: if (!$uname) { $uname=$env{'user.name'}; }
4475: my $uhome=&homeserver($uname,$udomain);
4476: my %newstorehash;
1.800 albertel 4477: foreach my $item (keys(%$storehash)) {
4478: my $key = $version.':'.&escape($symb).':'.$item;
4479: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4480: }
4481: my $items='';
4482: my %allitems = ();
1.800 albertel 4483: foreach my $item (keys(%newstorehash)) {
4484: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4485: my $key = $1.':keys:'.$2;
4486: $allitems{$key} .= $3.':';
4487: }
1.800 albertel 4488: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4489: }
1.800 albertel 4490: foreach my $item (keys(%allitems)) {
4491: $allitems{$item} =~ s/\:$//;
4492: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4493: }
4494: $items=~s/\&$//;
4495: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4496: }
4497:
1.47 www 4498: # ------------------------------------------------------ critical put interface
4499:
4500: sub cput {
1.134 albertel 4501: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4502: if (!$udomain) { $udomain=$env{'user.domain'}; }
4503: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4504: my $uhome=&homeserver($uname,$udomain);
1.47 www 4505: my $items='';
1.800 albertel 4506: foreach my $item (keys(%$storehash)) {
4507: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4508: }
1.47 www 4509: $items=~s/\&$//;
1.134 albertel 4510: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4511: }
4512:
4513: # -------------------------------------------------------------- eget interface
4514:
4515: sub eget {
1.133 albertel 4516: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4517: my $items='';
1.800 albertel 4518: foreach my $item (@$storearr) {
4519: $items.=&escape($item).'&';
1.191 harris41 4520: }
1.12 www 4521: $items=~s/\&$//;
1.620 albertel 4522: if (!$udomain) { $udomain=$env{'user.domain'}; }
4523: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4524: my $uhome=&homeserver($uname,$udomain);
4525: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4526: my @pairs=split(/\&/,$rep);
4527: my %returnhash=();
1.42 www 4528: my $i=0;
1.800 albertel 4529: foreach my $item (@$storearr) {
4530: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4531: $i++;
1.191 harris41 4532: }
1.12 www 4533: return %returnhash;
4534: }
4535:
1.667 albertel 4536: # ------------------------------------------------------------ tmpput interface
4537: sub tmpput {
1.802 raeburn 4538: my ($storehash,$server,$context)=@_;
1.667 albertel 4539: my $items='';
1.800 albertel 4540: foreach my $item (keys(%$storehash)) {
4541: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4542: }
4543: $items=~s/\&$//;
1.802 raeburn 4544: if (defined($context)) {
4545: $items .= ':'.&escape($context);
4546: }
1.667 albertel 4547: return &reply("tmpput:$items",$server);
4548: }
4549:
4550: # ------------------------------------------------------------ tmpget interface
4551: sub tmpget {
1.688 albertel 4552: my ($token,$server)=@_;
4553: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4554: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4555: my %returnhash;
4556: foreach my $item (split(/\&/,$rep)) {
4557: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4558: next if ($key =~ /^error: 2 /);
1.667 albertel 4559: $returnhash{&unescape($key)}=&thaw_unescape($value);
4560: }
4561: return %returnhash;
4562: }
4563:
1.688 albertel 4564: # ------------------------------------------------------------ tmpget interface
4565: sub tmpdel {
4566: my ($token,$server)=@_;
4567: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4568: return &reply("tmpdel:$token",$server);
4569: }
4570:
1.765 albertel 4571: # -------------------------------------------------- portfolio access checking
4572:
4573: sub portfolio_access {
1.766 albertel 4574: my ($requrl) = @_;
1.765 albertel 4575: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4576: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4577: if ($result) {
4578: my %setters;
4579: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4580: my ($startblock,$endblock) =
4581: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4582: if ($startblock && $endblock) {
4583: return 'B';
4584: }
4585: } else {
4586: my ($startblock,$endblock) =
4587: &Apache::loncommon::blockcheck(\%setters,'port');
4588: if ($startblock && $endblock) {
4589: return 'B';
4590: }
4591: }
4592: }
1.765 albertel 4593: if ($result eq 'ok') {
1.766 albertel 4594: return 'F';
1.765 albertel 4595: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4596: return 'A';
1.765 albertel 4597: }
1.766 albertel 4598: return '';
1.765 albertel 4599: }
4600:
4601: sub get_portfolio_access {
1.767 albertel 4602: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4603:
4604: if (!ref($access_hash)) {
4605: my $current_perms = &get_portfile_permissions($udom,$unum);
4606: my %access_controls = &get_access_controls($current_perms,$group,
4607: $file_name);
4608: $access_hash = $access_controls{$file_name};
4609: }
4610:
1.765 albertel 4611: my ($public,$guest,@domains,@users,@courses,@groups);
4612: my $now = time;
4613: if (ref($access_hash) eq 'HASH') {
4614: foreach my $key (keys(%{$access_hash})) {
4615: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4616: if ($start > $now) {
4617: next;
4618: }
4619: if ($end && $end<$now) {
4620: next;
4621: }
4622: if ($scope eq 'public') {
4623: $public = $key;
4624: last;
4625: } elsif ($scope eq 'guest') {
4626: $guest = $key;
4627: } elsif ($scope eq 'domains') {
4628: push(@domains,$key);
4629: } elsif ($scope eq 'users') {
4630: push(@users,$key);
4631: } elsif ($scope eq 'course') {
4632: push(@courses,$key);
4633: } elsif ($scope eq 'group') {
4634: push(@groups,$key);
4635: }
4636: }
4637: if ($public) {
4638: return 'ok';
4639: }
4640: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4641: if ($guest) {
4642: return $guest;
4643: }
4644: } else {
4645: if (@domains > 0) {
4646: foreach my $domkey (@domains) {
4647: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4648: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4649: return 'ok';
4650: }
4651: }
4652: }
4653: }
4654: if (@users > 0) {
4655: foreach my $userkey (@users) {
1.865 raeburn 4656: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4657: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4658: if (ref($item) eq 'HASH') {
4659: if (($item->{'uname'} eq $env{'user.name'}) &&
4660: ($item->{'udom'} eq $env{'user.domain'})) {
4661: return 'ok';
4662: }
4663: }
4664: }
4665: }
1.765 albertel 4666: }
4667: }
4668: my %roleshash;
4669: my @courses_and_groups = @courses;
4670: push(@courses_and_groups,@groups);
4671: if (@courses_and_groups > 0) {
4672: my (%allgroups,%allroles);
4673: my ($start,$end,$role,$sec,$group);
4674: foreach my $envkey (%env) {
1.1056.2.2 raeburn 4675: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4676: my $cid = $2.'_'.$3;
4677: if ($1 eq 'gr') {
4678: $group = $4;
4679: $allgroups{$cid}{$group} = $env{$envkey};
4680: } else {
4681: if ($4 eq '') {
4682: $sec = 'none';
4683: } else {
4684: $sec = $4;
4685: }
4686: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4687: }
1.811 albertel 4688: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4689: my $cid = $2.'_'.$3;
4690: if ($4 eq '') {
4691: $sec = 'none';
4692: } else {
4693: $sec = $4;
4694: }
4695: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4696: }
4697: }
4698: if (keys(%allroles) == 0) {
4699: return;
4700: }
4701: foreach my $key (@courses_and_groups) {
4702: my %content = %{$$access_hash{$key}};
4703: my $cnum = $content{'number'};
4704: my $cdom = $content{'domain'};
4705: my $cid = $cdom.'_'.$cnum;
4706: if (!exists($allroles{$cid})) {
4707: next;
4708: }
4709: foreach my $role_id (keys(%{$content{'roles'}})) {
4710: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4711: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4712: my @status = @{$content{'roles'}{$role_id}{'access'}};
4713: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4714: foreach my $role (keys(%{$allroles{$cid}})) {
4715: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4716: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4717: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4718: if (grep/^all$/,@sections) {
4719: return 'ok';
4720: } else {
4721: if (grep/^$sec$/,@sections) {
4722: return 'ok';
4723: }
4724: }
4725: }
4726: }
4727: if (keys(%{$allgroups{$cid}}) == 0) {
4728: if (grep/^none$/,@groups) {
4729: return 'ok';
4730: }
4731: } else {
4732: if (grep/^all$/,@groups) {
4733: return 'ok';
4734: }
4735: foreach my $group (keys(%{$allgroups{$cid}})) {
4736: if (grep/^$group$/,@groups) {
4737: return 'ok';
4738: }
4739: }
4740: }
4741: }
4742: }
4743: }
4744: }
4745: }
4746: if ($guest) {
4747: return $guest;
4748: }
4749: }
4750: }
4751: return;
4752: }
4753:
4754: sub course_group_datechecker {
4755: my ($dates,$now,$status) = @_;
4756: my ($start,$end) = split(/\./,$dates);
4757: if (!$start && !$end) {
4758: return 'ok';
4759: }
4760: if (grep/^active$/,@{$status}) {
4761: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4762: return 'ok';
4763: }
4764: }
4765: if (grep/^previous$/,@{$status}) {
4766: if ($end > $now ) {
4767: return 'ok';
4768: }
4769: }
4770: if (grep/^future$/,@{$status}) {
4771: if ($start > $now) {
4772: return 'ok';
4773: }
4774: }
4775: return;
4776: }
4777:
4778: sub parse_portfolio_url {
4779: my ($url) = @_;
4780:
4781: my ($type,$udom,$unum,$group,$file_name);
4782:
1.823 albertel 4783: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4784: $type = 1;
4785: $udom = $1;
4786: $unum = $2;
4787: $file_name = $3;
1.823 albertel 4788: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4789: $type = 2;
4790: $udom = $1;
4791: $unum = $2;
4792: $group = $3;
4793: $file_name = $3.'/'.$4;
4794: }
4795: if (wantarray) {
4796: return ($type,$udom,$unum,$file_name,$group);
4797: }
4798: return $type;
4799: }
4800:
4801: sub is_portfolio_url {
4802: my ($url) = @_;
4803: return scalar(&parse_portfolio_url($url));
4804: }
4805:
1.798 raeburn 4806: sub is_portfolio_file {
4807: my ($file) = @_;
1.820 raeburn 4808: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4809: return 1;
4810: }
4811: return;
4812: }
4813:
1.976 raeburn 4814: sub usertools_access {
1.985 raeburn 4815: my ($uname,$udom,$tool,$action,$context) = @_;
4816: my ($access,%tools);
4817: if ($context eq '') {
4818: $context = 'tools';
4819: }
4820: if ($context eq 'requestcourses') {
4821: %tools = (
4822: official => 1,
4823: unofficial => 1,
1.1006 raeburn 4824: community => 1,
1.985 raeburn 4825: );
4826: } else {
4827: %tools = (
4828: aboutme => 1,
4829: blog => 1,
4830: portfolio => 1,
4831: );
4832: }
1.976 raeburn 4833: return if (!defined($tools{$tool}));
4834:
4835: if ((!defined($udom)) || (!defined($uname))) {
4836: $udom = $env{'user.domain'};
4837: $uname = $env{'user.name'};
4838: }
4839:
1.978 raeburn 4840: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4841: if ($action ne 'reload') {
1.985 raeburn 4842: if ($context eq 'requestcourses') {
4843: return $env{'environment.canrequest.'.$tool};
4844: } else {
4845: return $env{'environment.availabletools.'.$tool};
4846: }
4847: }
1.976 raeburn 4848: }
4849:
4850: my ($toolstatus,$inststatus);
4851:
1.985 raeburn 4852: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4853: ($action ne 'reload')) {
4854: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4855: $inststatus = $env{'environment.inststatus'};
4856: } else {
1.1025 raeburn 4857: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4858: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4859: $inststatus = $userenv{'inststatus'};
4860: }
4861:
4862: if ($toolstatus ne '') {
4863: if ($toolstatus) {
4864: $access = 1;
4865: } else {
4866: $access = 0;
4867: }
4868: return $access;
4869: }
4870:
4871: my $is_adv = &is_advanced_user($udom,$uname);
4872: my %domdef = &get_domain_defaults($udom);
4873: if (ref($domdef{$tool}) eq 'HASH') {
4874: if ($is_adv) {
4875: if ($domdef{$tool}{'_LC_adv'} ne '') {
4876: if ($domdef{$tool}{'_LC_adv'}) {
4877: $access = 1;
4878: } else {
4879: $access = 0;
4880: }
4881: return $access;
4882: }
4883: }
4884: if ($inststatus ne '') {
4885: my ($hasaccess,$hasnoaccess);
4886: foreach my $affiliation (split(/:/,$inststatus)) {
4887: if ($domdef{$tool}{$affiliation} ne '') {
4888: if ($domdef{$tool}{$affiliation}) {
4889: $hasaccess = 1;
4890: } else {
4891: $hasnoaccess = 1;
4892: }
4893: }
4894: }
4895: if ($hasaccess || $hasnoaccess) {
4896: if ($hasaccess) {
4897: $access = 1;
4898: } elsif ($hasnoaccess) {
4899: $access = 0;
4900: }
4901: return $access;
4902: }
4903: } else {
4904: if ($domdef{$tool}{'default'} ne '') {
4905: if ($domdef{$tool}{'default'}) {
4906: $access = 1;
4907: } elsif ($domdef{$tool}{'default'} == 0) {
4908: $access = 0;
4909: }
4910: return $access;
4911: }
4912: }
4913: } else {
1.985 raeburn 4914: if ($context eq 'tools') {
4915: $access = 1;
4916: } else {
4917: $access = 0;
4918: }
1.976 raeburn 4919: return $access;
4920: }
4921: }
4922:
1.1050 raeburn 4923: sub is_course_owner {
4924: my ($cdom,$cnum,$udom,$uname) = @_;
4925: if (($udom eq '') || ($uname eq '')) {
4926: $udom = $env{'user.domain'};
4927: $uname = $env{'user.name'};
4928: }
4929: unless (($udom eq '') || ($uname eq '')) {
4930: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
4931: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
4932: return 1;
4933: } else {
4934: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
4935: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
4936: return 1;
4937: }
4938: }
4939: }
4940: }
4941: return;
4942: }
4943:
1.976 raeburn 4944: sub is_advanced_user {
4945: my ($udom,$uname) = @_;
4946: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4947: my %allroles;
4948: my $is_adv;
4949: foreach my $role (keys(%roleshash)) {
4950: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4951: my $area = '/'.$tdomain.'/'.$trest;
4952: if ($sec ne '') {
4953: $area .= '/'.$sec;
4954: }
4955: if (($area ne '') && ($trole ne '')) {
4956: my $spec=$trole.'.'.$area;
4957: if ($trole =~ /^cr\//) {
4958: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4959: } elsif ($trole ne 'gr') {
4960: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4961: }
4962: }
4963: }
4964: foreach my $role (keys(%allroles)) {
4965: last if ($is_adv);
4966: foreach my $item (split(/:/,$allroles{$role})) {
4967: if ($item ne '') {
4968: my ($privilege,$restrictions)=split(/&/,$item);
4969: if ($privilege eq 'adv') {
4970: $is_adv = 1;
4971: last;
4972: }
4973: }
4974: }
4975: }
4976: return $is_adv;
4977: }
1.798 raeburn 4978:
1.1035 raeburn 4979: sub check_can_request {
1.1036 raeburn 4980: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 4981: my $canreq = 0;
4982: my ($types,$typename) = &Apache::loncommon::course_types();
4983: my @options = ('approval','validate','autolimit');
4984: my $optregex = join('|',@options);
4985: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
4986: foreach my $type (@{$types}) {
4987: if (&usertools_access($env{'user.name'},
4988: $env{'user.domain'},
4989: $type,undef,'requestcourses')) {
4990: $canreq ++;
1.1036 raeburn 4991: if (ref($request_domains) eq 'HASH') {
4992: push(@{$request_domains->{$type}},$env{'user.domain'});
4993: }
1.1035 raeburn 4994: if ($dom eq $env{'user.domain'}) {
4995: $can_request->{$type} = 1;
4996: }
4997: }
4998: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
4999: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5000: if (@curr > 0) {
1.1036 raeburn 5001: foreach my $item (@curr) {
5002: if (ref($request_domains) eq 'HASH') {
5003: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5004: if ($otherdom ne '') {
5005: if (ref($request_domains->{$type}) eq 'ARRAY') {
5006: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5007: push(@{$request_domains->{$type}},$otherdom);
5008: }
5009: } else {
5010: push(@{$request_domains->{$type}},$otherdom);
5011: }
5012: }
5013: }
5014: }
5015: unless($dom eq $env{'user.domain'}) {
5016: $canreq ++;
1.1035 raeburn 5017: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5018: $can_request->{$type} = 1;
5019: }
5020: }
5021: }
5022: }
5023: }
5024: }
5025: return $canreq;
5026: }
5027:
1.341 www 5028: # ---------------------------------------------- Custom access rule evaluation
5029:
5030: sub customaccess {
5031: my ($priv,$uri)=@_;
1.807 albertel 5032: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5033: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5034: $udom = &LONCAPA::clean_domain($udom);
5035: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5036: my $access=0;
1.800 albertel 5037: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5038: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5039: if ($type eq 'user') {
5040: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5041: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5042: if ($tdom) {
5043: if ($tdom ne $env{'user.domain'}) { next; }
5044: }
1.896 albertel 5045: if ($tuname) {
5046: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5047: }
5048: $access=($effect eq 'allow');
5049: last;
5050: }
5051: } else {
5052: if ($role) {
5053: if ($role ne $urole) { next; }
5054: }
5055: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5056: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5057: if ($tdom) {
5058: if ($tdom ne $udom) { next; }
5059: }
5060: if ($tcrs) {
5061: if ($tcrs ne $ucrs) { next; }
5062: }
5063: if ($tsec) {
5064: if ($tsec ne $usec) { next; }
5065: }
5066: $access=($effect eq 'allow');
5067: last;
5068: }
5069: if ($realm eq '' && $role eq '') {
5070: $access=($effect eq 'allow');
5071: }
1.402 bowersj2 5072: }
1.341 www 5073: }
5074: return $access;
5075: }
5076:
1.103 harris41 5077: # ------------------------------------------------- Check for a user privilege
1.12 www 5078:
5079: sub allowed {
1.810 raeburn 5080: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5081: my $ver_orguri=$uri;
1.439 www 5082: $uri=&deversion($uri);
1.152 www 5083: my $orguri=$uri;
1.52 www 5084: $uri=&declutter($uri);
1.809 raeburn 5085:
1.810 raeburn 5086: if ($priv eq 'evb') {
5087: # Evade communication block restrictions for specified role in a course
5088: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5089: return $1;
5090: } else {
5091: return;
5092: }
5093: }
5094:
1.620 albertel 5095: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5096: # Free bre access to adm and meta resources
1.775 albertel 5097: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5098: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5099: && ($priv eq 'bre')) {
1.14 www 5100: return 'F';
1.159 www 5101: }
5102:
1.545 banghart 5103: # Free bre access to user's own portfolio contents
1.714 raeburn 5104: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5105: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5106: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5107: my %setters;
5108: my ($startblock,$endblock) =
5109: &Apache::loncommon::blockcheck(\%setters,'port');
5110: if ($startblock && $endblock) {
5111: return 'B';
5112: } else {
5113: return 'F';
5114: }
1.545 banghart 5115: }
5116:
1.762 raeburn 5117: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5118: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5119: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5120: if (exists($env{'request.course.id'})) {
5121: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5122: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5123: if (($domain eq $cdom) && ($name eq $cnum)) {
5124: my $courseprivid=$env{'request.course.id'};
5125: $courseprivid=~s/\_/\//;
5126: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5127: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5128: return $1;
1.762 raeburn 5129: } else {
5130: if ($env{'request.course.sec'}) {
5131: $courseprivid.='/'.$env{'request.course.sec'};
5132: }
5133: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5134: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5135: return $2;
5136: }
1.714 raeburn 5137: }
5138: }
5139: }
5140: }
5141:
1.159 www 5142: # Free bre to public access
5143:
5144: if ($priv eq 'bre') {
1.238 www 5145: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5146: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5147: return 'F';
5148: }
1.238 www 5149: if ($copyright eq 'priv') {
5150: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5151: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5152: return '';
5153: }
5154: }
5155: if ($copyright eq 'domain') {
5156: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5157: unless (($env{'user.domain'} eq $1) ||
5158: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5159: return '';
5160: }
1.262 matthew 5161: }
1.620 albertel 5162: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5163: # Library role, so allow browsing of resources in this domain.
5164: return 'F';
1.238 www 5165: }
1.341 www 5166: if ($copyright eq 'custom') {
5167: unless (&customaccess($priv,$uri)) { return ''; }
5168: }
1.14 www 5169: }
1.264 matthew 5170: # Domain coordinator is trying to create a course
1.620 albertel 5171: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5172: # uri is the requested domain in this case.
5173: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5174: # a role of dc for the domain in question.
1.620 albertel 5175: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5176: }
1.29 www 5177:
1.52 www 5178: my $thisallowed='';
5179: my $statecond=0;
5180: my $courseprivid='';
5181:
1.1039 raeburn 5182: my $ownaccess;
1.1043 raeburn 5183: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5184: if (($priv eq 'bro') && ($env{'user.author'})) {
5185: if ($uri eq '') {
5186: $ownaccess = 1;
5187: } else {
5188: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5189: my $udom = $env{'user.domain'};
5190: my $uname = $env{'user.name'};
5191: if ($uri =~ m{^\Q$udom\E/?$}) {
5192: $ownaccess = 1;
1.1040 raeburn 5193: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5194: unless ($uri =~ m{\.\./}) {
5195: $ownaccess = 1;
5196: }
5197: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5198: my $now = time;
5199: if ($uri =~ m{^([^/]+)/?$}) {
5200: my $adom = $1;
5201: foreach my $key (keys(%env)) {
1.1042 raeburn 5202: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5203: my ($start,$end) = split('.',$env{$key});
5204: if (($now >= $start) && (!$end || $end < $now)) {
5205: $ownaccess = 1;
5206: last;
5207: }
5208: }
5209: }
5210: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5211: my $adom = $1;
5212: my $aname = $2;
1.1042 raeburn 5213: foreach my $role ('ca','aa') {
5214: if ($env{"user.role.$role./$adom/$aname"}) {
5215: my ($start,$end) =
5216: split('.',$env{"user.role.$role./$adom/$aname"});
5217: if (($now >= $start) && (!$end || $end < $now)) {
5218: $ownaccess = 1;
5219: last;
5220: }
1.1039 raeburn 5221: }
5222: }
5223: }
5224: }
5225: }
5226: }
5227: }
5228:
1.52 www 5229: # Course
5230:
1.620 albertel 5231: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5232: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5233: $thisallowed.=$1;
5234: }
1.52 www 5235: }
1.29 www 5236:
1.52 www 5237: # Domain
5238:
1.620 albertel 5239: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5240: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5241: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5242: $thisallowed.=$1;
5243: }
1.12 www 5244: }
1.52 www 5245:
5246: # Course: uri itself is a course
1.66 www 5247: my $courseuri=$uri;
5248: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5249: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5250:
1.620 albertel 5251: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5252: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5253: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5254: $thisallowed.=$1;
5255: }
1.12 www 5256: }
1.29 www 5257:
1.665 albertel 5258: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5259: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5260: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5261: $thisallowed='';
1.671 raeburn 5262: my ($match)=&is_on_map($uri);
5263: if ($match) {
5264: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5265: =~/\Q$priv\E\&([^\:]*)/) {
5266: $thisallowed.=$1;
5267: }
5268: } else {
1.705 albertel 5269: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5270: if ($refuri) {
5271: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5272: $thisallowed='F';
1.671 raeburn 5273: } else {
5274: $refuri=&declutter($refuri);
5275: my ($match) = &is_on_map($refuri);
5276: if ($match) {
5277: $thisallowed='F';
5278: }
1.669 raeburn 5279: }
1.671 raeburn 5280: }
5281: }
1.314 www 5282: }
1.492 albertel 5283:
1.766 albertel 5284: if ($priv eq 'bre'
5285: && $thisallowed ne 'F'
5286: && $thisallowed ne '2'
5287: && &is_portfolio_url($uri)) {
5288: $thisallowed = &portfolio_access($uri);
5289: }
5290:
1.52 www 5291: # Full access at system, domain or course-wide level? Exit.
1.29 www 5292: if ($thisallowed=~/F/) {
5293: return 'F';
5294: }
5295:
1.52 www 5296: # If this is generating or modifying users, exit with special codes
1.29 www 5297:
1.643 www 5298: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5299: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5300: my ($audom,$auname)=split('/',$uri);
1.643 www 5301: # no author name given, so this just checks on the general right to make a co-author in this domain
5302: unless ($auname) { return $thisallowed; }
5303: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5304: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5305: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5306: ($audom ne $env{'request.role.domain'}))) { return ''; }
5307: }
1.52 www 5308: return $thisallowed;
5309: }
5310: #
1.103 harris41 5311: # Gathered so far: system, domain and course wide privileges
1.52 www 5312: #
5313: # Course: See if uri or referer is an individual resource that is part of
5314: # the course
5315:
1.620 albertel 5316: if ($env{'request.course.id'}) {
1.232 www 5317:
1.620 albertel 5318: $courseprivid=$env{'request.course.id'};
5319: if ($env{'request.course.sec'}) {
5320: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5321: }
5322: $courseprivid=~s/\_/\//;
5323: my $checkreferer=1;
1.232 www 5324: my ($match,$cond)=&is_on_map($uri);
5325: if ($match) {
5326: $statecond=$cond;
1.620 albertel 5327: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5328: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5329: $thisallowed.=$1;
5330: $checkreferer=0;
5331: }
1.29 www 5332: }
1.83 www 5333:
1.148 www 5334: if ($checkreferer) {
1.620 albertel 5335: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5336: unless ($refuri) {
1.800 albertel 5337: foreach my $key (keys(%env)) {
5338: if ($key=~/^httpref\..*\*/) {
5339: my $pattern=$key;
1.156 www 5340: $pattern=~s/^httpref\.\/res\///;
1.148 www 5341: $pattern=~s/\*/\[\^\/\]\+/g;
5342: $pattern=~s/\//\\\//g;
1.152 www 5343: if ($orguri=~/$pattern/) {
1.800 albertel 5344: $refuri=$env{$key};
1.148 www 5345: }
5346: }
1.191 harris41 5347: }
1.148 www 5348: }
1.232 www 5349:
1.148 www 5350: if ($refuri) {
1.152 www 5351: $refuri=&declutter($refuri);
1.232 www 5352: my ($match,$cond)=&is_on_map($refuri);
5353: if ($match) {
5354: my $refstatecond=$cond;
1.620 albertel 5355: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5356: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5357: $thisallowed.=$1;
1.53 www 5358: $uri=$refuri;
5359: $statecond=$refstatecond;
1.52 www 5360: }
5361: }
1.148 www 5362: }
1.29 www 5363: }
1.52 www 5364: }
1.29 www 5365:
1.52 www 5366: #
1.103 harris41 5367: # Gathered now: all privileges that could apply, and condition number
1.52 www 5368: #
5369: #
5370: # Full or no access?
5371: #
1.29 www 5372:
1.52 www 5373: if ($thisallowed=~/F/) {
5374: return 'F';
5375: }
1.29 www 5376:
1.52 www 5377: unless ($thisallowed) {
5378: return '';
5379: }
1.29 www 5380:
1.52 www 5381: # Restrictions exist, deal with them
5382: #
5383: # C:according to course preferences
5384: # R:according to resource settings
5385: # L:unless locked
5386: # X:according to user session state
5387: #
5388:
5389: # Possibly locked functionality, check all courses
1.54 www 5390: # Locks might take effect only after 10 minutes cache expiration for other
5391: # courses, and 2 minutes for current course
1.52 www 5392:
5393: my $envkey;
5394: if ($thisallowed=~/L/) {
1.1000 raeburn 5395: foreach $envkey (keys(%env)) {
1.54 www 5396: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5397: my $courseid=$2;
5398: my $roleid=$1.'.'.$2;
1.92 www 5399: $courseid=~s/^\///;
1.54 www 5400: my $expiretime=600;
1.620 albertel 5401: if ($env{'request.role'} eq $roleid) {
1.54 www 5402: $expiretime=120;
5403: }
5404: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5405: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5406: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5407: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5408: }
1.620 albertel 5409: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5410: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5411: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5412: &log($env{'user.domain'},$env{'user.name'},
5413: $env{'user.home'},
1.57 www 5414: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5415: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5416: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5417: return '';
5418: }
5419: }
1.620 albertel 5420: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5421: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5422: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5423: &log($env{'user.domain'},$env{'user.name'},
5424: $env{'user.home'},
1.57 www 5425: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5426: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5427: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5428: return '';
5429: }
5430: }
5431: }
1.29 www 5432: }
1.52 www 5433: }
5434:
5435: #
5436: # Rest of the restrictions depend on selected course
5437: #
5438:
1.620 albertel 5439: unless ($env{'request.course.id'}) {
1.766 albertel 5440: if ($thisallowed eq 'A') {
5441: return 'A';
1.814 raeburn 5442: } elsif ($thisallowed eq 'B') {
5443: return 'B';
1.766 albertel 5444: } else {
5445: return '1';
5446: }
1.52 www 5447: }
1.29 www 5448:
1.52 www 5449: #
5450: # Now user is definitely in a course
5451: #
1.53 www 5452:
5453:
5454: # Course preferences
5455:
5456: if ($thisallowed=~/C/) {
1.620 albertel 5457: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5458: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5459: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5460: =~/\Q$rolecode\E/) {
1.689 albertel 5461: if ($priv ne 'pch') {
5462: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5463: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5464: $env{'request.course.id'});
5465: }
1.237 www 5466: return '';
5467: }
5468:
1.620 albertel 5469: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5470: =~/\Q$unamedom\E/) {
1.689 albertel 5471: if ($priv ne 'pch') {
5472: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5473: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5474: $env{'request.course.id'});
5475: }
1.54 www 5476: return '';
5477: }
1.53 www 5478: }
5479:
5480: # Resource preferences
5481:
5482: if ($thisallowed=~/R/) {
1.620 albertel 5483: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5484: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5485: if ($priv ne 'pch') {
5486: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5487: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5488: }
5489: return '';
1.54 www 5490: }
1.53 www 5491: }
1.30 www 5492:
1.246 www 5493: # Restricted by state or randomout?
1.30 www 5494:
1.52 www 5495: if ($thisallowed=~/X/) {
1.620 albertel 5496: if ($env{'acc.randomout'}) {
1.579 albertel 5497: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5498: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5499: return '';
5500: }
1.247 www 5501: }
5502: if (&condval($statecond)) {
1.52 www 5503: return '2';
5504: } else {
5505: return '';
5506: }
5507: }
1.30 www 5508:
1.766 albertel 5509: if ($thisallowed eq 'A') {
5510: return 'A';
1.814 raeburn 5511: } elsif ($thisallowed eq 'B') {
5512: return 'B';
1.766 albertel 5513: }
1.52 www 5514: return 'F';
1.232 www 5515: }
5516:
1.710 albertel 5517: sub split_uri_for_cond {
5518: my $uri=&deversion(&declutter(shift));
5519: my @uriparts=split(/\//,$uri);
5520: my $filename=pop(@uriparts);
5521: my $pathname=join('/',@uriparts);
5522: return ($pathname,$filename);
5523: }
1.232 www 5524: # --------------------------------------------------- Is a resource on the map?
5525:
5526: sub is_on_map {
1.710 albertel 5527: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5528: #Trying to find the conditional for the file
1.620 albertel 5529: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5530: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5531: if ($match) {
1.289 bowersj2 5532: return (1,$1);
5533: } else {
1.434 www 5534: return (0,0);
1.289 bowersj2 5535: }
1.12 www 5536: }
5537:
1.427 www 5538: # --------------------------------------------------------- Get symb from alias
5539:
5540: sub get_symb_from_alias {
5541: my $symb=shift;
5542: my ($map,$resid,$url)=&decode_symb($symb);
5543: # Already is a symb
5544: if ($url) { return $symb; }
5545: # Must be an alias
5546: my $aliassymb='';
5547: my %bighash;
1.620 albertel 5548: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5549: &GDBM_READER(),0640)) {
5550: my $rid=$bighash{'mapalias_'.$symb};
5551: if ($rid) {
5552: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5553: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5554: $resid,$bighash{'src_'.$rid});
1.427 www 5555: }
5556: untie %bighash;
5557: }
5558: return $aliassymb;
5559: }
5560:
1.12 www 5561: # ----------------------------------------------------------------- Define Role
5562:
5563: sub definerole {
5564: if (allowed('mcr','/')) {
5565: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5566: foreach my $role (split(':',$sysrole)) {
5567: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5568: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5569: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5570: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5571: return "refused:s:$crole&$cqual";
5572: }
5573: }
1.191 harris41 5574: }
1.800 albertel 5575: foreach my $role (split(':',$domrole)) {
5576: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5577: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5578: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5579: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5580: return "refused:d:$crole&$cqual";
5581: }
5582: }
1.191 harris41 5583: }
1.800 albertel 5584: foreach my $role (split(':',$courole)) {
5585: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5586: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5587: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5588: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5589: return "refused:c:$crole&$cqual";
5590: }
5591: }
1.191 harris41 5592: }
1.620 albertel 5593: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5594: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5595: "rolesdef_$rolename=".
5596: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5597: return reply($command,$env{'user.home'});
1.12 www 5598: } else {
5599: return 'refused';
5600: }
1.105 harris41 5601: }
5602:
5603: # ---------------- Make a metadata query against the network of library servers
5604:
5605: sub metadata_query {
1.244 matthew 5606: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5607: my %rhash;
1.845 albertel 5608: my %libserv = &all_library();
1.244 matthew 5609: my @server_list = (defined($server_array) ? @$server_array
5610: : keys(%libserv) );
5611: for my $server (@server_list) {
1.118 harris41 5612: unless ($custom or $customshow) {
5613: my $reply=&reply("querysend:".&escape($query),$server);
5614: $rhash{$server}=$reply;
5615: }
5616: else {
5617: my $reply=&reply("querysend:".&escape($query).':'.
5618: &escape($custom).':'.&escape($customshow),
5619: $server);
5620: $rhash{$server}=$reply;
5621: }
1.112 harris41 5622: }
1.118 harris41 5623: return \%rhash;
1.240 www 5624: }
5625:
5626: # ----------------------------------------- Send log queries and wait for reply
5627:
5628: sub log_query {
5629: my ($uname,$udom,$query,%filters)=@_;
5630: my $uhome=&homeserver($uname,$udom);
5631: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5632: my $uhost=&hostname($uhome);
1.800 albertel 5633: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5634: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5635: $uhome);
1.479 albertel 5636: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5637: return get_query_reply($queryid);
5638: }
5639:
1.818 raeburn 5640: # -------------------------- Update MySQL table for portfolio file
5641:
5642: sub update_portfolio_table {
1.821 raeburn 5643: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5644: if ($group ne '') {
5645: $file_name =~s /^\Q$group\E//;
5646: }
1.818 raeburn 5647: my $homeserver = &homeserver($uname,$udom);
5648: my $queryid=
1.821 raeburn 5649: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5650: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5651: my $reply = &get_query_reply($queryid);
5652: return $reply;
5653: }
5654:
1.899 raeburn 5655: # -------------------------- Update MySQL allusers table
5656:
5657: sub update_allusers_table {
5658: my ($uname,$udom,$names) = @_;
5659: my $homeserver = &homeserver($uname,$udom);
5660: my $queryid=
5661: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5662: 'lastname='.&escape($names->{'lastname'}).'%%'.
5663: 'firstname='.&escape($names->{'firstname'}).'%%'.
5664: 'middlename='.&escape($names->{'middlename'}).'%%'.
5665: 'generation='.&escape($names->{'generation'}).'%%'.
5666: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5667: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.2.6 raeburn 5668: return;
1.899 raeburn 5669: }
5670:
1.508 raeburn 5671: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5672:
5673: sub fetch_enrollment_query {
1.511 raeburn 5674: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5675: my $homeserver;
1.547 raeburn 5676: my $maxtries = 1;
1.508 raeburn 5677: if ($context eq 'automated') {
5678: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5679: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5680: } else {
5681: $homeserver = &homeserver($cnum,$dom);
5682: }
1.838 albertel 5683: my $host=&hostname($homeserver);
1.506 raeburn 5684: my $cmd = '';
1.1000 raeburn 5685: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5686: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5687: }
5688: $cmd =~ s/%%$//;
5689: $cmd = &escape($cmd);
5690: my $query = 'fetchenrollment';
1.620 albertel 5691: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5692: unless ($queryid=~/^\Q$host\E\_/) {
5693: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5694: return 'error: '.$queryid;
5695: }
1.506 raeburn 5696: my $reply = &get_query_reply($queryid);
1.547 raeburn 5697: my $tries = 1;
5698: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5699: $reply = &get_query_reply($queryid);
5700: $tries ++;
5701: }
1.526 raeburn 5702: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5703: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5704: } else {
1.901 albertel 5705: my @responses = split(/:/,$reply);
1.515 raeburn 5706: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5707: foreach my $line (@responses) {
5708: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5709: $$replyref{$key} = $value;
5710: }
5711: } else {
1.506 raeburn 5712: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5713: foreach my $line (@responses) {
5714: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5715: $$replyref{$key} = $value;
5716: if ($value > 0) {
1.800 albertel 5717: foreach my $item (@{$$affiliatesref{$key}}) {
5718: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5719: my $destname = $pathname.'/'.$filename;
5720: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5721: if ($xml_classlist =~ /^error/) {
5722: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5723: } else {
1.506 raeburn 5724: if ( open(FILE,">$destname") ) {
5725: print FILE &unescape($xml_classlist);
5726: close(FILE);
1.526 raeburn 5727: } else {
5728: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5729: }
5730: }
5731: }
5732: }
5733: }
5734: }
5735: return 'ok';
5736: }
5737: return 'error';
5738: }
5739:
1.242 www 5740: sub get_query_reply {
5741: my $queryid=shift;
1.240 www 5742: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5743: my $reply='';
5744: for (1..100) {
5745: sleep 2;
5746: if (-e $replyfile.'.end') {
1.448 albertel 5747: if (open(my $fh,$replyfile)) {
1.904 albertel 5748: $reply = join('',<$fh>);
5749: close($fh);
1.240 www 5750: } else { return 'error: reply_file_error'; }
1.242 www 5751: return &unescape($reply);
5752: }
1.240 www 5753: }
1.242 www 5754: return 'timeout:'.$queryid;
1.240 www 5755: }
5756:
5757: sub courselog_query {
1.241 www 5758: #
5759: # possible filters:
5760: # url: url or symb
5761: # username
5762: # domain
5763: # action: view, submit, grade
5764: # start: timestamp
5765: # end: timestamp
5766: #
1.240 www 5767: my (%filters)=@_;
1.620 albertel 5768: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5769: if ($filters{'url'}) {
5770: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5771: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5772: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5773: }
1.620 albertel 5774: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5775: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5776: return &log_query($cname,$cdom,'courselog',%filters);
5777: }
5778:
5779: sub userlog_query {
1.858 raeburn 5780: #
5781: # possible filters:
5782: # action: log check role
5783: # start: timestamp
5784: # end: timestamp
5785: #
1.240 www 5786: my ($uname,$udom,%filters)=@_;
5787: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5788: }
5789:
1.506 raeburn 5790: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5791:
5792: sub auto_run {
1.508 raeburn 5793: my ($cnum,$cdom) = @_;
1.876 raeburn 5794: my $response = 0;
5795: my $settings;
5796: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5797: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5798: $settings = $domconfig{'autoenroll'};
5799: if ($settings->{'run'} eq '1') {
5800: $response = 1;
5801: }
5802: } else {
1.934 raeburn 5803: my $homeserver;
5804: if (&is_course($cdom,$cnum)) {
5805: $homeserver = &homeserver($cnum,$cdom);
5806: } else {
5807: $homeserver = &domain($cdom,'primary');
5808: }
5809: if ($homeserver ne 'no_host') {
5810: $response = &reply('autorun:'.$cdom,$homeserver);
5811: }
1.876 raeburn 5812: }
1.506 raeburn 5813: return $response;
5814: }
1.776 albertel 5815:
1.506 raeburn 5816: sub auto_get_sections {
1.508 raeburn 5817: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5818: my $homeserver;
5819: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5820: $homeserver = &homeserver($cnum,$cdom);
5821: }
5822: if (!defined($homeserver)) {
5823: if ($cdom =~ /^$match_domain$/) {
5824: $homeserver = &domain($cdom,'primary');
5825: }
5826: }
5827: my @secs;
5828: if (defined($homeserver)) {
5829: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5830: unless ($response eq 'refused') {
5831: @secs = split(/:/,$response);
5832: }
1.506 raeburn 5833: }
5834: return @secs;
5835: }
1.776 albertel 5836:
1.506 raeburn 5837: sub auto_new_course {
1.508 raeburn 5838: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5839: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5840: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5841: return $response;
5842: }
1.776 albertel 5843:
1.506 raeburn 5844: sub auto_validate_courseID {
1.508 raeburn 5845: my ($cnum,$cdom,$inst_course_id) = @_;
5846: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5847: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5848: return $response;
5849: }
1.776 albertel 5850:
1.1007 raeburn 5851: sub auto_validate_instcode {
1.1020 raeburn 5852: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5853: my ($homeserver,$response);
5854: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5855: $homeserver = &homeserver($cnum,$cdom);
5856: }
5857: if (!defined($homeserver)) {
5858: if ($cdom =~ /^$match_domain$/) {
5859: $homeserver = &domain($cdom,'primary');
5860: }
5861: }
1.1056.2.4 raeburn 5862: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5863: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5864: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5865: return ($outcome,$description);
1.1007 raeburn 5866: }
5867:
1.506 raeburn 5868: sub auto_create_password {
1.873 raeburn 5869: my ($cnum,$cdom,$authparam,$udom) = @_;
5870: my ($homeserver,$response);
1.506 raeburn 5871: my $create_passwd = 0;
5872: my $authchk = '';
1.873 raeburn 5873: if ($udom =~ /^$match_domain$/) {
5874: $homeserver = &domain($udom,'primary');
5875: }
5876: if ($homeserver eq '') {
5877: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5878: $homeserver = &homeserver($cnum,$cdom);
5879: }
5880: }
5881: if ($homeserver eq '') {
5882: $authchk = 'nodomain';
1.506 raeburn 5883: } else {
1.873 raeburn 5884: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5885: if ($response eq 'refused') {
5886: $authchk = 'refused';
5887: } else {
1.901 albertel 5888: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5889: }
1.506 raeburn 5890: }
5891: return ($authparam,$create_passwd,$authchk);
5892: }
5893:
1.706 raeburn 5894: sub auto_photo_permission {
5895: my ($cnum,$cdom,$students) = @_;
5896: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5897: my ($outcome,$perm_reqd,$conditions) =
5898: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5899: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5900: return (undef,undef);
5901: }
1.706 raeburn 5902: return ($outcome,$perm_reqd,$conditions);
5903: }
5904:
5905: sub auto_checkphotos {
5906: my ($uname,$udom,$pid) = @_;
5907: my $homeserver = &homeserver($uname,$udom);
5908: my ($result,$resulttype);
5909: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5910: &escape($uname).':'.&escape($pid),
5911: $homeserver));
1.709 albertel 5912: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5913: return (undef,undef);
5914: }
1.706 raeburn 5915: if ($outcome) {
5916: ($result,$resulttype) = split(/:/,$outcome);
5917: }
5918: return ($result,$resulttype);
5919: }
5920:
5921: sub auto_photochoice {
5922: my ($cnum,$cdom) = @_;
5923: my $homeserver = &homeserver($cnum,$cdom);
5924: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5925: &escape($cdom),
5926: $homeserver)));
1.709 albertel 5927: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5928: return (undef,undef);
5929: }
1.706 raeburn 5930: return ($update,$comment);
5931: }
5932:
5933: sub auto_photoupdate {
5934: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5935: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5936: my $host=&hostname($homeserver);
1.706 raeburn 5937: my $cmd = '';
5938: my $maxtries = 1;
1.800 albertel 5939: foreach my $affiliate (keys(%{$affiliatesref})) {
5940: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5941: }
5942: $cmd =~ s/%%$//;
5943: $cmd = &escape($cmd);
5944: my $query = 'institutionalphotos';
5945: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5946: unless ($queryid=~/^\Q$host\E\_/) {
5947: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5948: return 'error: '.$queryid;
5949: }
5950: my $reply = &get_query_reply($queryid);
5951: my $tries = 1;
5952: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5953: $reply = &get_query_reply($queryid);
5954: $tries ++;
5955: }
5956: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5957: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5958: } else {
5959: my @responses = split(/:/,$reply);
5960: my $outcome = shift(@responses);
5961: foreach my $item (@responses) {
5962: my ($key,$value) = split(/=/,$item);
5963: $$photo{$key} = $value;
5964: }
5965: return $outcome;
5966: }
5967: return 'error';
5968: }
5969:
1.521 raeburn 5970: sub auto_instcode_format {
1.793 albertel 5971: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5972: $cat_order) = @_;
1.521 raeburn 5973: my $courses = '';
1.772 raeburn 5974: my @homeservers;
1.521 raeburn 5975: if ($caller eq 'global') {
1.841 albertel 5976: my %servers = &get_servers($codedom,'library');
5977: foreach my $tryserver (keys(%servers)) {
5978: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5979: push(@homeservers,$tryserver);
5980: }
1.584 raeburn 5981: }
1.1022 raeburn 5982: } elsif ($caller eq 'requests') {
5983: if ($codedom =~ /^$match_domain$/) {
5984: my $chome = &domain($codedom,'primary');
5985: unless ($chome eq 'no_host') {
5986: push(@homeservers,$chome);
5987: }
5988: }
1.521 raeburn 5989: } else {
1.772 raeburn 5990: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5991: }
1.793 albertel 5992: foreach my $code (keys(%{$instcodes})) {
5993: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5994: }
5995: chop($courses);
1.772 raeburn 5996: my $ok_response = 0;
5997: my $response;
5998: while (@homeservers > 0 && $ok_response == 0) {
5999: my $server = shift(@homeservers);
6000: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6001: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6002: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6003: split(/:/,$response);
1.772 raeburn 6004: %{$codes} = (%{$codes},&str2hash($codes_str));
6005: push(@{$codetitles},&str2array($codetitles_str));
6006: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6007: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6008: $ok_response = 1;
6009: }
6010: }
6011: if ($ok_response) {
1.521 raeburn 6012: return 'ok';
1.772 raeburn 6013: } else {
6014: return $response;
1.521 raeburn 6015: }
6016: }
6017:
1.792 raeburn 6018: sub auto_instcode_defaults {
6019: my ($domain,$returnhash,$code_order) = @_;
6020: my @homeservers;
1.841 albertel 6021:
6022: my %servers = &get_servers($domain,'library');
6023: foreach my $tryserver (keys(%servers)) {
6024: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6025: push(@homeservers,$tryserver);
6026: }
1.792 raeburn 6027: }
1.841 albertel 6028:
1.792 raeburn 6029: my $response;
1.841 albertel 6030: foreach my $server (@homeservers) {
1.792 raeburn 6031: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6032: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6033:
6034: foreach my $pair (split(/\&/,$response)) {
6035: my ($name,$value)=split(/\=/,$pair);
6036: if ($name eq 'code_order') {
6037: @{$code_order} = split(/\&/,&unescape($value));
6038: } else {
6039: $returnhash->{&unescape($name)}=&unescape($value);
6040: }
6041: }
6042: return 'ok';
1.792 raeburn 6043: }
1.841 albertel 6044:
6045: return $response;
1.1003 raeburn 6046: }
6047:
6048: sub auto_possible_instcodes {
1.1007 raeburn 6049: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6050: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6051: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6052: return;
6053: }
1.1003 raeburn 6054: my (@homeservers,$uhome);
6055: if (defined(&domain($domain,'primary'))) {
6056: $uhome=&domain($domain,'primary');
6057: push(@homeservers,&domain($domain,'primary'));
6058: } else {
6059: my %servers = &get_servers($domain,'library');
6060: foreach my $tryserver (keys(%servers)) {
6061: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6062: push(@homeservers,$tryserver);
6063: }
6064: }
6065: }
6066: my $response;
6067: foreach my $server (@homeservers) {
6068: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6069: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6070: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6071: split(':',$response);
6072: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6073: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6074: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6075: my ($name,$value)=split('=',$item);
6076: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6077: }
6078: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6079: my ($name,$value)=split('=',$item);
6080: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6081: }
6082: return 'ok';
6083: }
6084: return $response;
6085: }
1.792 raeburn 6086:
1.1010 raeburn 6087: sub auto_courserequest_checks {
6088: my ($dom) = @_;
1.1020 raeburn 6089: my ($homeserver,%validations);
6090: if ($dom =~ /^$match_domain$/) {
6091: $homeserver = &domain($dom,'primary');
6092: }
6093: unless ($homeserver eq 'no_host') {
6094: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6095: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6096: my @items = split(/&/,$response);
6097: foreach my $item (@items) {
6098: my ($key,$value) = split('=',$item);
6099: $validations{&unescape($key)} = &thaw_unescape($value);
6100: }
6101: }
6102: }
1.1010 raeburn 6103: return %validations;
6104: }
6105:
1.1020 raeburn 6106: sub auto_courserequest_validation {
6107: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6108: my ($homeserver,$response);
6109: if ($dom =~ /^$match_domain$/) {
6110: $homeserver = &domain($dom,'primary');
6111: }
6112: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6113:
1.1020 raeburn 6114: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6115: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6116: ':'.&escape($instcode).':'.&escape($instseclist),
6117: $homeserver));
6118: }
6119: return $response;
6120: }
6121:
1.777 albertel 6122: sub auto_validate_class_sec {
1.918 raeburn 6123: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6124: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6125: my $ownerlist;
6126: if (ref($owners) eq 'ARRAY') {
6127: $ownerlist = join(',',@{$owners});
6128: } else {
6129: $ownerlist = $owners;
6130: }
1.773 raeburn 6131: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6132: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6133: return $response;
6134: }
6135:
1.679 raeburn 6136: # ------------------------------------------------------- Course Group routines
6137:
6138: sub get_coursegroups {
1.809 raeburn 6139: my ($cdom,$cnum,$group,$namespace) = @_;
6140: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6141: }
6142:
1.679 raeburn 6143: sub modify_coursegroup {
6144: my ($cdom,$cnum,$groupsettings) = @_;
6145: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6146: }
6147:
1.809 raeburn 6148: sub toggle_coursegroup_status {
6149: my ($cdom,$cnum,$group,$action) = @_;
6150: my ($from_namespace,$to_namespace);
6151: if ($action eq 'delete') {
6152: $from_namespace = 'coursegroups';
6153: $to_namespace = 'deleted_groups';
6154: } else {
6155: $from_namespace = 'deleted_groups';
6156: $to_namespace = 'coursegroups';
6157: }
6158: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6159: if (my $tmp = &error(%curr_group)) {
6160: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6161: return ('read error',$tmp);
6162: } else {
6163: my %savedsettings = %curr_group;
1.809 raeburn 6164: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6165: my $deloutcome;
6166: if ($result eq 'ok') {
1.809 raeburn 6167: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6168: } else {
6169: return ('write error',$result);
6170: }
6171: if ($deloutcome eq 'ok') {
6172: return 'ok';
6173: } else {
6174: return ('delete error',$deloutcome);
6175: }
6176: }
6177: }
6178:
1.679 raeburn 6179: sub modify_group_roles {
1.957 raeburn 6180: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6181: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6182: my $role = 'gr/'.&escape($userprivs);
6183: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6184: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6185: if ($result eq 'ok') {
6186: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6187: }
1.679 raeburn 6188: return $result;
6189: }
6190:
6191: sub modify_coursegroup_membership {
6192: my ($cdom,$cnum,$membership) = @_;
6193: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6194: return $result;
6195: }
6196:
1.682 raeburn 6197: sub get_active_groups {
6198: my ($udom,$uname,$cdom,$cnum) = @_;
6199: my $now = time;
6200: my %groups = ();
6201: foreach my $key (keys(%env)) {
1.811 albertel 6202: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6203: my ($start,$end) = split(/\./,$env{$key});
6204: if (($end!=0) && ($end<$now)) { next; }
6205: if (($start!=0) && ($start>$now)) { next; }
6206: if ($1 eq $cdom && $2 eq $cnum) {
6207: $groups{$3} = $env{$key} ;
6208: }
6209: }
6210: }
6211: return %groups;
6212: }
6213:
1.683 raeburn 6214: sub get_group_membership {
6215: my ($cdom,$cnum,$group) = @_;
6216: return(&dump('groupmembership',$cdom,$cnum,$group));
6217: }
6218:
6219: sub get_users_groups {
6220: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6221: my @usersgroups;
1.683 raeburn 6222: my $cachetime=1800;
6223:
6224: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6225: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6226: if (defined($cached)) {
1.734 albertel 6227: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6228: } else {
6229: $grouplist = '';
1.816 raeburn 6230: my $courseurl = &courseid_to_courseurl($courseid);
6231: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6232: my $access_end = $env{'course.'.$courseid.
6233: '.default_enrollment_end_date'};
6234: my $now = time;
6235: foreach my $key (keys(%roleshash)) {
6236: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6237: my $group = $1;
6238: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6239: my $start = $2;
6240: my $end = $1;
6241: if ($start == -1) { next; } # deleted from group
6242: if (($start!=0) && ($start>$now)) { next; }
6243: if (($end!=0) && ($end<$now)) {
6244: if ($access_end && $access_end < $now) {
6245: if ($access_end - $end < 86400) {
6246: push(@usersgroups,$group);
1.733 raeburn 6247: }
6248: }
1.817 raeburn 6249: next;
1.733 raeburn 6250: }
1.817 raeburn 6251: push(@usersgroups,$group);
1.683 raeburn 6252: }
6253: }
6254: }
1.817 raeburn 6255: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6256: $grouplist = join(':',@usersgroups);
6257: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6258: }
1.733 raeburn 6259: return @usersgroups;
1.683 raeburn 6260: }
6261:
6262: sub devalidate_getgroups_cache {
6263: my ($udom,$uname,$cdom,$cnum)=@_;
6264: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6265:
1.683 raeburn 6266: my $hashid="$udom:$uname:$courseid";
6267: &devalidate_cache_new('getgroups',$hashid);
6268: }
6269:
1.12 www 6270: # ------------------------------------------------------------------ Plain Text
6271:
6272: sub plaintext {
1.988 raeburn 6273: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6274: if ($short =~ m{^cr/}) {
1.758 albertel 6275: return (split('/',$short))[-1];
6276: }
1.742 raeburn 6277: if (!defined($cid)) {
6278: $cid = $env{'request.course.id'};
6279: }
6280: my %rolenames = (
1.1008 raeburn 6281: Course => 'std',
6282: Community => 'alt1',
1.742 raeburn 6283: );
1.1037 raeburn 6284: if ($cid ne '') {
6285: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6286: unless ($forcedefault) {
6287: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6288: &Apache::lonlocal::mt_escape(\$roletext);
6289: return &Apache::lonlocal::mt($roletext);
6290: }
6291: }
6292: }
6293: if ((defined($type)) && (defined($rolenames{$type})) &&
6294: (defined($rolenames{$type})) &&
6295: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6296: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6297: } elsif ($cid ne '') {
6298: my $crstype = $env{'course.'.$cid.'.type'};
6299: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6300: (defined($prp{$short}{$rolenames{$crstype}}))) {
6301: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6302: }
1.742 raeburn 6303: }
1.1037 raeburn 6304: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6305: }
6306:
6307: # ----------------------------------------------------------------- Assign Role
6308:
6309: sub assignrole {
1.957 raeburn 6310: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6311: $context)=@_;
1.21 www 6312: my $mrole;
6313: if ($role =~ /^cr\//) {
1.393 www 6314: my $cwosec=$url;
1.811 albertel 6315: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6316: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6317: my $refused = 1;
6318: if ($context eq 'requestcourses') {
6319: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6320: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6321: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6322: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6323: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6324: if ($crsenv{'internal.courseowner'} eq
6325: $env{'user.name'}.':'.$env{'user.domain'}) {
6326: $refused = '';
6327: }
6328: }
6329: }
6330: }
6331: }
6332: if ($refused) {
6333: &logthis('Refused custom assignrole: '.
6334: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6335: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6336: return 'refused';
6337: }
1.104 www 6338: }
1.21 www 6339: $mrole='cr';
1.678 raeburn 6340: } elsif ($role =~ /^gr\//) {
6341: my $cwogrp=$url;
1.811 albertel 6342: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6343: unless (&allowed('mdg',$cwogrp)) {
6344: &logthis('Refused group assignrole: '.
6345: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6346: $env{'user.name'}.' at '.$env{'user.domain'});
6347: return 'refused';
6348: }
6349: $mrole='gr';
1.21 www 6350: } else {
1.82 www 6351: my $cwosec=$url;
1.811 albertel 6352: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6353: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6354: my $refused;
6355: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6356: if (!(&allowed('c'.$role,$url))) {
6357: $refused = 1;
6358: }
6359: } else {
6360: $refused = 1;
6361: }
1.947 raeburn 6362: if ($refused) {
1.1045 raeburn 6363: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6364: if (!$selfenroll && $context eq 'course') {
6365: my %crsenv;
6366: if ($role eq 'cc' || $role eq 'co') {
6367: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6368: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6369: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6370: if ($crsenv{'internal.courseowner'} eq
6371: $env{'user.name'}.':'.$env{'user.domain'}) {
6372: $refused = '';
6373: }
6374: }
6375: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6376: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6377: if ($crsenv{'internal.courseowner'} eq
6378: $env{'user.name'}.':'.$env{'user.domain'}) {
6379: $refused = '';
6380: }
6381: }
6382: }
6383: }
6384: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6385: $refused = '';
1.1017 raeburn 6386: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6387: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6388: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6389: my $wrongcc;
6390: if ($cnum =~ /^$match_community$/) {
6391: $wrongcc = 1 if ($role eq 'cc');
6392: } else {
6393: $wrongcc = 1 if ($role eq 'co');
6394: }
6395: unless ($wrongcc) {
6396: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6397: if ($crsenv{'internal.courseowner'} eq
6398: $env{'user.name'}.':'.$env{'user.domain'}) {
6399: $refused = '';
6400: }
1.1017 raeburn 6401: }
6402: }
6403: }
6404: if ($refused) {
1.947 raeburn 6405: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6406: ' '.$role.' '.$end.' '.$start.' by '.
6407: $env{'user.name'}.' at '.$env{'user.domain'});
6408: return 'refused';
6409: }
1.932 raeburn 6410: }
1.104 www 6411: }
1.21 www 6412: $mrole=$role;
6413: }
1.620 albertel 6414: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6415: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6416: if ($end) { $command.='_'.$end; }
1.21 www 6417: if ($start) {
6418: if ($end) {
1.81 www 6419: $command.='_'.$start;
1.21 www 6420: } else {
1.81 www 6421: $command.='_0_'.$start;
1.21 www 6422: }
6423: }
1.739 raeburn 6424: my $origstart = $start;
6425: my $origend = $end;
1.957 raeburn 6426: my $delflag;
1.357 www 6427: # actually delete
6428: if ($deleteflag) {
1.373 www 6429: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6430: # modify command to delete the role
1.620 albertel 6431: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6432: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6433: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6434: # set start and finish to negative values for userrolelog
6435: $start=-1;
6436: $end=-1;
1.957 raeburn 6437: $delflag = 1;
1.357 www 6438: }
6439: }
6440: # send command
1.349 www 6441: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6442: # log new user role if status is ok
1.349 www 6443: if ($answer eq 'ok') {
1.663 raeburn 6444: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6445: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6446: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6447: unless ($role =~ /^gr/) {
6448: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6449: $origstart,$selfenroll,$context);
1.739 raeburn 6450: }
1.1053 raeburn 6451: if ($role eq 'cc') {
6452: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6453: }
1.349 www 6454: }
6455: return $answer;
1.169 harris41 6456: }
6457:
1.1053 raeburn 6458: sub autoupdate_coowners {
6459: my ($url,$end,$start,$uname,$udom) = @_;
6460: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6461: if (($cdom ne '') && ($cnum ne '')) {
6462: my $now = time;
6463: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6464: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6465: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6466: my $instcode = $coursehash{'internal.coursecode'};
6467: if ($instcode ne '') {
1.1056 raeburn 6468: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6469: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6470: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6471: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6472: if ($result eq 'valid') {
6473: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6474: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6475: push(@newcoowners,$coowner);
6476: }
6477: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6478: push(@newcoowners,$uname.':'.$udom);
6479: }
6480: @newcoowners = sort(@newcoowners);
6481: } else {
6482: push(@newcoowners,$uname.':'.$udom);
6483: }
6484: } else {
6485: if ($coursehash{'internal.co-owners'}) {
6486: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6487: unless ($coowner eq $uname.':'.$udom) {
6488: push(@newcoowners,$coowner);
6489: }
6490: }
6491: unless (@newcoowners > 0) {
6492: $delcoowners = 1;
6493: $coowners = '';
6494: }
6495: }
6496: }
6497: if (@newcoowners || $delcoowners) {
6498: &store_coowners($cdom,$cnum,$coursehash{'home'},
6499: $delcoowners,@newcoowners);
6500: }
6501: }
6502: }
6503: }
6504: }
6505: }
6506: }
6507:
6508: sub store_coowners {
6509: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6510: my $cid = $cdom.'_'.$cnum;
6511: my ($coowners,$delresult,$putresult);
6512: if (@newcoowners) {
6513: $coowners = join(',',@newcoowners);
6514: my %coownershash = (
6515: 'internal.co-owners' => $coowners,
6516: );
6517: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6518: if ($putresult eq 'ok') {
6519: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6520: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6521: }
6522: }
6523: }
6524: if ($delcoowners) {
6525: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6526: if ($delresult eq 'ok') {
6527: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6528: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6529: }
6530: }
6531: }
6532: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6533: my %crsinfo =
6534: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6535: if (ref($crsinfo{$cid}) eq 'HASH') {
6536: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6537: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6538: }
6539: }
6540: }
6541:
1.169 harris41 6542: # -------------------------------------------------- Modify user authentication
1.197 www 6543: # Overrides without validation
6544:
1.169 harris41 6545: sub modifyuserauth {
6546: my ($udom,$uname,$umode,$upass)=@_;
6547: my $uhome=&homeserver($uname,$udom);
1.197 www 6548: unless (&allowed('mau',$udom)) { return 'refused'; }
6549: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6550: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6551: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6552: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6553: &escape($upass),$uhome);
1.620 albertel 6554: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6555: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6556: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6557: &log($udom,,$uname,$uhome,
1.620 albertel 6558: 'Authentication changed by '.$env{'user.domain'}.', '.
6559: $env{'user.name'}.', '.$umode.
1.197 www 6560: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6561: unless ($reply eq 'ok') {
1.197 www 6562: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6563: return 'error: '.$reply;
6564: }
1.170 harris41 6565: return 'ok';
1.80 www 6566: }
6567:
1.81 www 6568: # --------------------------------------------------------------- Modify a user
1.80 www 6569:
1.81 www 6570: sub modifyuser {
1.206 matthew 6571: my ($udom, $uname, $uid,
6572: $umode, $upass, $first,
6573: $middle, $last, $gene,
1.1056.2.1 raeburn 6574: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6575: $udom= &LONCAPA::clean_domain($udom);
6576: $uname=&LONCAPA::clean_username($uname);
1.1056.2.1 raeburn 6577: my $showcandelete = 'none';
6578: if (ref($candelete) eq 'ARRAY') {
6579: if (@{$candelete} > 0) {
6580: $showcandelete = join(', ',@{$candelete});
6581: }
6582: }
1.81 www 6583: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6584: $umode.', '.$first.', '.$middle.', '.
1.1056.2.1 raeburn 6585: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6586: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6587: ' desiredhome not specified').
1.620 albertel 6588: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6589: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6590: my $uhome=&homeserver($uname,$udom,'true');
1.1056.2.6 raeburn 6591: my $newuser;
6592: if ($uhome eq 'no_host') {
6593: $newuser = 1;
6594: }
1.80 www 6595: # ----------------------------------------------------------------- Create User
1.406 albertel 6596: if (($uhome eq 'no_host') &&
6597: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6598: my $unhome='';
1.844 albertel 6599: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6600: $unhome = $desiredhome;
1.620 albertel 6601: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6602: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6603: } else { # load balancing routine for determining $unhome
1.81 www 6604: my $loadm=10000000;
1.841 albertel 6605: my %servers = &get_servers($udom,'library');
6606: foreach my $tryserver (keys(%servers)) {
6607: my $answer=reply('load',$tryserver);
6608: if (($answer=~/\d+/) && ($answer<$loadm)) {
6609: $loadm=$answer;
6610: $unhome=$tryserver;
6611: }
1.80 www 6612: }
6613: }
6614: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6615: return 'error: unable to find a home server for '.$uname.
6616: ' in domain '.$udom;
1.80 www 6617: }
6618: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6619: &escape($upass),$unhome);
6620: unless ($reply eq 'ok') {
6621: return 'error: '.$reply;
6622: }
1.230 stredwic 6623: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6624: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6625: return 'error: unable verify users home machine.';
1.80 www 6626: }
1.209 matthew 6627: } # End of creation of new user
1.80 www 6628: # ---------------------------------------------------------------------- Add ID
6629: if ($uid) {
6630: $uid=~tr/A-Z/a-z/;
6631: my %uidhash=&idrget($udom,$uname);
1.196 www 6632: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6633: && (!$forceid)) {
1.80 www 6634: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6635: return 'error: user id "'.$uid.'" does not match '.
6636: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6637: }
6638: } else {
6639: &idput($udom,($uname => $uid));
6640: }
6641: }
6642: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6643: my @tmp=&get('environment',
1.899 raeburn 6644: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6645: 'permanentemail','inststatus'],
1.134 albertel 6646: $udom,$uname);
1.1056.2.6 raeburn 6647: my (%names,%oldnames);
1.313 matthew 6648: if ($tmp[0] =~ m/^error:.*/) {
6649: %names=();
6650: } else {
6651: %names = @tmp;
1.1056.2.6 raeburn 6652: %oldnames = %names;
1.313 matthew 6653: }
1.388 www 6654: #
1.1056.2.1 raeburn 6655: # If name, email and/or uid are blank (e.g., because an uploaded file
6656: # of users did not contain them), do not overwrite existing values
6657: # unless field is in $candelete array ref.
6658: #
6659: my @fields = ('firstname','middlename','lastname','generation',
6660: 'permanentemail','id');
6661: my %newvalues;
6662: if (ref($candelete) eq 'ARRAY') {
6663: foreach my $field (@fields) {
6664: if (grep(/^\Q$field\E$/,@{$candelete})) {
6665: if ($field eq 'firstname') {
6666: $names{$field} = $first;
6667: } elsif ($field eq 'middlename') {
6668: $names{$field} = $middle;
6669: } elsif ($field eq 'lastname') {
6670: $names{$field} = $last;
6671: } elsif ($field eq 'generation') {
6672: $names{$field} = $gene;
6673: } elsif ($field eq 'permanentemail') {
6674: $names{$field} = $email;
6675: } elsif ($field eq 'id') {
6676: $names{$field} = $uid;
6677: }
6678: }
6679: }
6680: }
6681:
1.388 www 6682: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6683: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6684: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6685: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6686: if ($email) {
6687: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6688: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6689: }
1.899 raeburn 6690: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6691: if (defined($inststatus)) {
6692: $names{'inststatus'} = '';
6693: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6694: if (ref($usertypes) eq 'HASH') {
6695: my @okstatuses;
6696: foreach my $item (split(/:/,$inststatus)) {
6697: if (defined($usertypes->{$item})) {
6698: push(@okstatuses,$item);
6699: }
6700: }
6701: if (@okstatuses) {
6702: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6703: }
6704: }
6705: }
1.1056.2.6 raeburn 6706: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6707: $umode.', '.$first.', '.$middle.', '.
6708: $last.', '.$gene.', '.$email.', '.$inststatus;
6709: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6710: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6711: } else {
6712: $logmsg .= ' during self creation';
6713: }
1.1056.2.6 raeburn 6714: my $changed;
6715: if ($newuser) {
6716: $changed = 1;
6717: } else {
6718: foreach my $field (@fields) {
6719: if ($names{$field} ne $oldnames{$field}) {
6720: $changed = 1;
6721: last;
6722: }
6723: }
6724: }
6725: unless ($changed) {
6726: $logmsg = 'No changes in user information needed for: '.$logmsg;
6727: &logthis($logmsg);
6728: return 'ok';
6729: }
6730: my $reply = &put('environment', \%names, $udom,$uname);
6731: if ($reply ne 'ok') {
6732: return 'error: '.$reply;
6733: }
1.1056.2.7 raeburn 6734: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
6735: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
6736: }
1.1056.2.6 raeburn 6737: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6738: &devalidate_cache_new('namescache',$uname.':'.$udom);
6739: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6740: &logthis($logmsg);
1.134 albertel 6741: return 'ok';
1.80 www 6742: }
6743:
1.81 www 6744: # -------------------------------------------------------------- Modify student
1.80 www 6745:
1.81 www 6746: sub modifystudent {
6747: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6748: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6749: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6750: if (!$cid) {
1.620 albertel 6751: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6752: return 'not_in_class';
6753: }
1.80 www 6754: }
6755: # --------------------------------------------------------------- Make the user
1.81 www 6756: my $reply=&modifyuser
1.209 matthew 6757: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6758: $desiredhome,$email,$inststatus);
1.80 www 6759: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6760: # This will cause &modify_student_enrollment to get the uid from the
6761: # students environment
6762: $uid = undef if (!$forceid);
1.455 albertel 6763: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6764: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6765: return $reply;
6766: }
6767:
6768: sub modify_student_enrollment {
1.957 raeburn 6769: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6770: my ($cdom,$cnum,$chome);
6771: if (!$cid) {
1.620 albertel 6772: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6773: return 'not_in_class';
6774: }
1.620 albertel 6775: $cdom=$env{'course.'.$cid.'.domain'};
6776: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6777: } else {
6778: ($cdom,$cnum)=split(/_/,$cid);
6779: }
1.620 albertel 6780: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6781: if (!$chome) {
1.457 raeburn 6782: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6783: }
1.455 albertel 6784: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6785: # Make sure the user exists
1.81 www 6786: my $uhome=&homeserver($uname,$udom);
6787: if (($uhome eq '') || ($uhome eq 'no_host')) {
6788: return 'error: no such user';
6789: }
1.297 matthew 6790: # Get student data if we were not given enough information
6791: if (!defined($first) || $first eq '' ||
6792: !defined($last) || $last eq '' ||
6793: !defined($uid) || $uid eq '' ||
6794: !defined($middle) || $middle eq '' ||
6795: !defined($gene) || $gene eq '') {
1.294 matthew 6796: # They did not supply us with enough data to enroll the student, so
6797: # we need to pick up more information.
1.297 matthew 6798: my %tmp = &get('environment',
1.294 matthew 6799: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6800: ,$udom,$uname);
6801:
1.800 albertel 6802: #foreach my $key (keys(%tmp)) {
6803: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6804: #}
1.294 matthew 6805: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6806: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6807: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6808: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6809: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6810: }
1.556 albertel 6811: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6812: my $reply=cput('classlist',
6813: {"$uname:$udom" =>
1.515 raeburn 6814: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6815: $cdom,$cnum);
1.81 www 6816: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6817: return 'error: '.$reply;
1.652 albertel 6818: } else {
6819: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6820: }
1.297 matthew 6821: # Add student role to user
1.83 www 6822: my $uurl='/'.$cid;
1.81 www 6823: $uurl=~s/\_/\//g;
6824: if ($usec) {
6825: $uurl.='/'.$usec;
6826: }
1.957 raeburn 6827: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6828: }
6829:
1.556 albertel 6830: sub format_name {
6831: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6832: my $name;
6833: if ($first ne 'lastname') {
6834: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6835: } else {
6836: if ($lastname=~/\S/) {
6837: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6838: $name=~s/\s+,/,/;
6839: } else {
6840: $name.= $firstname.' '.$middlename.' '.$generation;
6841: }
6842: }
6843: $name=~s/^\s+//;
6844: $name=~s/\s+$//;
6845: $name=~s/\s+/ /g;
6846: return $name;
6847: }
6848:
1.84 www 6849: # ------------------------------------------------- Write to course preferences
6850:
6851: sub writecoursepref {
6852: my ($courseid,%prefs)=@_;
6853: $courseid=~s/^\///;
6854: $courseid=~s/\_/\//g;
6855: my ($cdomain,$cnum)=split(/\//,$courseid);
6856: my $chome=homeserver($cnum,$cdomain);
6857: if (($chome eq '') || ($chome eq 'no_host')) {
6858: return 'error: no such course';
6859: }
6860: my $cstring='';
1.800 albertel 6861: foreach my $pref (keys(%prefs)) {
6862: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6863: }
1.84 www 6864: $cstring=~s/\&$//;
6865: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6866: }
6867:
6868: # ---------------------------------------------------------- Make/modify course
6869:
6870: sub createcourse {
1.741 raeburn 6871: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6872: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6873: $url=&declutter($url);
6874: my $cid='';
1.1028 raeburn 6875: if ($context eq 'requestcourses') {
6876: my $can_create = 0;
6877: my ($ownername,$ownerdom) = split(':',$course_owner);
6878: if ($udom eq $ownerdom) {
6879: if (&usertools_access($ownername,$ownerdom,$category,undef,
6880: $context)) {
6881: $can_create = 1;
6882: }
6883: } else {
6884: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6885: $category);
6886: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6887: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6888: if (@curr > 0) {
6889: my @options = qw(approval validate autolimit);
6890: my $optregex = join('|',@options);
6891: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6892: $can_create = 1;
6893: }
6894: }
6895: }
6896: }
6897: if ($can_create) {
6898: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6899: unless (&allowed('ccc',$udom)) {
6900: return 'refused';
6901: }
1.1017 raeburn 6902: }
6903: } else {
6904: return 'refused';
6905: }
1.1028 raeburn 6906: } elsif (!&allowed('ccc',$udom)) {
6907: return 'refused';
1.84 www 6908: }
1.1011 raeburn 6909: # --------------------------------------------------------------- Get Unique ID
6910: my $uname;
6911: if ($cnum =~ /^$match_courseid$/) {
6912: my $chome=&homeserver($cnum,$udom,'true');
6913: if (($chome eq '') || ($chome eq 'no_host')) {
6914: $uname = $cnum;
6915: } else {
1.1038 raeburn 6916: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6917: }
6918: } else {
1.1038 raeburn 6919: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6920: }
6921: return $uname if ($uname =~ /^error/);
6922: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6923: if (!defined($course_server)) {
6924: if (defined(&domain($udom,'primary'))) {
6925: $course_server = &domain($udom,'primary');
6926: } else {
6927: $course_server = $env{'user.home'};
6928: }
6929: }
6930: my %host_servers =
6931: &Apache::lonnet::get_servers($udom,'library');
6932: unless ($host_servers{$course_server}) {
6933: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 6934: }
1.84 www 6935: # ------------------------------------------------------------- Make the course
6936: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 6937: $course_server);
1.84 www 6938: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 6939: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 6940: if (($uhome eq '') || ($uhome eq 'no_host')) {
6941: return 'error: no such course';
6942: }
1.271 www 6943: # ----------------------------------------------------------------- Course made
1.516 raeburn 6944: # log existence
1.1029 raeburn 6945: my $now = time;
1.918 raeburn 6946: my $newcourse = {
6947: $udom.'_'.$uname => {
1.921 raeburn 6948: description => $description,
6949: inst_code => $inst_code,
6950: owner => $course_owner,
6951: type => $crstype,
1.1029 raeburn 6952: creator => $env{'user.name'}.':'.
6953: $env{'user.domain'},
6954: created => $now,
6955: context => $context,
1.918 raeburn 6956: },
6957: };
1.921 raeburn 6958: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 6959: # set toplevel url
1.271 www 6960: my $topurl=$url;
6961: unless ($nonstandard) {
6962: # ------------------------------------------ For standard courses, make top url
6963: my $mapurl=&clutter($url);
1.278 www 6964: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 6965: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 6966: <map>
6967: <resource id="1" type="start"></resource>
6968: <resource id="2" src="$mapurl"></resource>
6969: <resource id="3" type="finish"></resource>
6970: <link index="1" from="1" to="2"></link>
6971: <link index="2" from="2" to="3"></link>
6972: </map>
6973: ENDINITMAP
6974: $topurl=&declutter(
1.638 albertel 6975: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 6976: );
6977: }
6978: # ----------------------------------------------------------- Write preferences
1.84 www 6979: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 6980: ('description' => $description,
6981: 'url' => $topurl,
6982: 'internal.creator' => $env{'user.name'}.':'.
6983: $env{'user.domain'},
6984: 'internal.created' => $now,
6985: 'internal.creationcontext' => $context)
6986: );
1.84 www 6987: return '/'.$udom.'/'.$uname;
6988: }
6989:
1.1011 raeburn 6990: # ------------------------------------------------------------------- Create ID
6991: sub generate_coursenum {
1.1038 raeburn 6992: my ($udom,$crstype) = @_;
1.1011 raeburn 6993: my $domdesc = &domain($udom);
6994: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 6995: my $first;
6996: if ($crstype eq 'Community') {
6997: $first = '0';
6998: } else {
6999: $first = int(1+rand(9));
7000: }
7001: my $uname=$first.
1.1011 raeburn 7002: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7003: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7004: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7005: # ----------------------------------------------- Make sure that does not exist
7006: my $uhome=&homeserver($uname,$udom,'true');
7007: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7008: if ($crstype eq 'Community') {
7009: $first = '0';
7010: } else {
7011: $first = int(1+rand(9));
7012: }
7013: $uname=$first.
1.1011 raeburn 7014: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7015: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7016: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7017: $uhome=&homeserver($uname,$udom,'true');
7018: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7019: return 'error: unable to generate unique course-ID';
7020: }
7021: }
7022: return $uname;
7023: }
7024:
1.813 albertel 7025: sub is_course {
7026: my ($cdom,$cnum) = @_;
7027: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7028: undef,'.');
1.813 albertel 7029: if (exists($courses{$cdom.'_'.$cnum})) {
7030: return 1;
7031: }
7032: return 0;
7033: }
7034:
1.1015 raeburn 7035: sub store_userdata {
7036: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7037: my $result;
1.1016 raeburn 7038: if ($datakey ne '') {
1.1013 raeburn 7039: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7040: if ($udom eq '' || $uname eq '') {
7041: $udom = $env{'user.domain'};
7042: $uname = $env{'user.name'};
7043: }
7044: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7045: if (($uhome eq '') || ($uhome eq 'no_host')) {
7046: $result = 'error: no_host';
7047: } else {
7048: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7049: $storehash->{'host'} = $perlvar{'lonHostID'};
7050:
7051: my $namevalue='';
7052: foreach my $key (keys(%{$storehash})) {
7053: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7054: }
7055: $namevalue=~s/\&$//;
7056: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7057: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7058: }
7059: } else {
7060: $result = 'error: data to store was not a hash reference';
7061: }
7062: } else {
7063: $result= 'error: invalid requestkey';
7064: }
7065: return $result;
7066: }
7067:
1.21 www 7068: # ---------------------------------------------------------- Assign Custom Role
7069:
7070: sub assigncustomrole {
1.957 raeburn 7071: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7072: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7073: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7074: }
7075:
7076: # ----------------------------------------------------------------- Revoke Role
7077:
7078: sub revokerole {
1.957 raeburn 7079: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7080: my $now=time;
1.965 raeburn 7081: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7082: }
7083:
7084: # ---------------------------------------------------------- Revoke Custom Role
7085:
7086: sub revokecustomrole {
1.957 raeburn 7087: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7088: my $now=time;
1.357 www 7089: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7090: $deleteflag,$selfenroll,$context);
1.17 www 7091: }
7092:
1.533 banghart 7093: # ------------------------------------------------------------ Disk usage
1.535 albertel 7094: sub diskusage {
1.955 raeburn 7095: my ($udom,$uname,$directorypath,$getpropath)=@_;
7096: $directorypath =~ s/\/$//;
7097: my $listing=&reply('du2:'.&escape($directorypath).':'
7098: .&escape($getpropath).':'.&escape($uname).':'
7099: .&escape($udom),homeserver($uname,$udom));
7100: if ($listing eq 'unknown_cmd') {
7101: if ($getpropath) {
7102: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7103: }
7104: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7105: }
1.514 albertel 7106: return $listing;
1.512 banghart 7107: }
7108:
1.566 banghart 7109: sub is_locked {
7110: my ($file_name, $domain, $user) = @_;
7111: my @check;
7112: my $is_locked;
7113: push @check, $file_name;
1.613 albertel 7114: my %locked = &get('file_permissions',\@check,
1.620 albertel 7115: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7116: my ($tmp)=keys(%locked);
7117: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7118:
1.566 banghart 7119: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7120: $is_locked = 'false';
7121: foreach my $entry (@{$locked{$file_name}}) {
7122: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7123: $is_locked = 'true';
7124: last;
1.745 raeburn 7125: }
7126: }
1.566 banghart 7127: } else {
7128: $is_locked = 'false';
7129: }
7130: }
7131:
1.759 albertel 7132: sub declutter_portfile {
7133: my ($file) = @_;
1.833 albertel 7134: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7135: return $file;
7136: }
7137:
1.559 banghart 7138: # ------------------------------------------------------------- Mark as Read Only
7139:
7140: sub mark_as_readonly {
7141: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7142: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7143: my ($tmp)=keys(%current_permissions);
7144: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7145: foreach my $file (@{$files}) {
1.759 albertel 7146: $file = &declutter_portfile($file);
1.561 banghart 7147: push(@{$current_permissions{$file}},$what);
1.559 banghart 7148: }
1.613 albertel 7149: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7150: return;
7151: }
7152:
1.572 banghart 7153: # ------------------------------------------------------------Save Selected Files
7154:
7155: sub save_selected_files {
7156: my ($user, $path, @files) = @_;
7157: my $filename = $user."savedfiles";
1.573 banghart 7158: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7159: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7160: foreach my $file (@files) {
1.620 albertel 7161: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7162: }
7163: foreach my $file (@other_files) {
1.574 banghart 7164: print (OUT $file."\n");
1.572 banghart 7165: }
1.574 banghart 7166: close (OUT);
1.572 banghart 7167: return 'ok';
7168: }
7169:
1.574 banghart 7170: sub clear_selected_files {
7171: my ($user) = @_;
7172: my $filename = $user."savedfiles";
7173: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7174: print (OUT undef);
7175: close (OUT);
7176: return ("ok");
7177: }
7178:
1.572 banghart 7179: sub files_in_path {
7180: my ($user, $path) = @_;
7181: my $filename = $user."savedfiles";
7182: my %return_files;
1.574 banghart 7183: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7184: while (my $line_in = <IN>) {
1.574 banghart 7185: chomp ($line_in);
7186: my @paths_and_file = split (m!/!, $line_in);
7187: my $file_part = pop (@paths_and_file);
7188: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7189: $path_part.='/';
7190: my $path_and_file = $path_part.$file_part;
7191: if ($path_part eq $path) {
7192: $return_files{$file_part}= 'selected';
7193: }
7194: }
1.574 banghart 7195: close (IN);
7196: return (\%return_files);
1.572 banghart 7197: }
7198:
7199: # called in portfolio select mode, to show files selected NOT in current directory
7200: sub files_not_in_path {
7201: my ($user, $path) = @_;
7202: my $filename = $user."savedfiles";
7203: my @return_files;
7204: my $path_part;
1.800 albertel 7205: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7206: while (my $line = <IN>) {
1.572 banghart 7207: #ok, I know it's clunky, but I want it to work
1.800 albertel 7208: my @paths_and_file = split(m|/|, $line);
7209: my $file_part = pop(@paths_and_file);
7210: chomp($file_part);
7211: my $path_part = join('/', @paths_and_file);
1.572 banghart 7212: $path_part .= '/';
7213: my $path_and_file = $path_part.$file_part;
7214: if ($path_part ne $path) {
1.800 albertel 7215: push(@return_files, ($path_and_file));
1.572 banghart 7216: }
7217: }
1.800 albertel 7218: close(OUT);
1.574 banghart 7219: return (@return_files);
1.572 banghart 7220: }
7221:
1.745 raeburn 7222: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7223:
1.745 raeburn 7224: sub get_portfile_permissions {
7225: my ($domain,$user) = @_;
1.613 albertel 7226: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7227: my ($tmp)=keys(%current_permissions);
7228: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7229: return \%current_permissions;
7230: }
7231:
7232: #---------------------------------------------Get portfolio file access controls
7233:
1.749 raeburn 7234: sub get_access_controls {
1.745 raeburn 7235: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7236: my %access;
7237: my $real_file = $file;
7238: $file =~ s/\.meta$//;
1.745 raeburn 7239: if (defined($file)) {
1.749 raeburn 7240: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7241: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7242: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7243: }
7244: }
1.745 raeburn 7245: } else {
1.749 raeburn 7246: foreach my $key (keys(%{$current_permissions})) {
7247: if ($key =~ /\0accesscontrol$/) {
7248: if (defined($group)) {
7249: if ($key !~ m-^\Q$group\E/-) {
7250: next;
7251: }
7252: }
7253: my ($fullpath) = split(/\0/,$key);
7254: if (ref($$current_permissions{$key}) eq 'HASH') {
7255: foreach my $control (keys(%{$$current_permissions{$key}})) {
7256: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7257: }
7258: }
7259: }
7260: }
7261: }
7262: return %access;
7263: }
7264:
7265: sub modify_access_controls {
7266: my ($file_name,$changes,$domain,$user)=@_;
7267: my ($outcome,$deloutcome);
7268: my %store_permissions;
7269: my %new_values;
7270: my %new_control;
7271: my %translation;
7272: my @deletions = ();
7273: my $now = time;
7274: if (exists($$changes{'activate'})) {
7275: if (ref($$changes{'activate'}) eq 'HASH') {
7276: my @newitems = sort(keys(%{$$changes{'activate'}}));
7277: my $numnew = scalar(@newitems);
7278: for (my $i=0; $i<$numnew; $i++) {
7279: my $newkey = $newitems[$i];
7280: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7281: if ($newkey =~ /^\d+:/) {
7282: $newkey =~ s/^(\d+)/$newid/;
7283: $translation{$1} = $newid;
7284: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7285: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7286: $translation{$1} = $newid;
7287: }
1.749 raeburn 7288: $new_values{$file_name."\0".$newkey} =
7289: $$changes{'activate'}{$newitems[$i]};
7290: $new_control{$newkey} = $now;
7291: }
7292: }
7293: }
7294: my %todelete;
7295: my %changed_items;
7296: foreach my $action ('delete','update') {
7297: if (exists($$changes{$action})) {
7298: if (ref($$changes{$action}) eq 'HASH') {
7299: foreach my $key (keys(%{$$changes{$action}})) {
7300: my ($itemnum) = ($key =~ /^([^:]+):/);
7301: if ($action eq 'delete') {
7302: $todelete{$itemnum} = 1;
7303: } else {
7304: $changed_items{$itemnum} = $key;
7305: }
7306: }
1.745 raeburn 7307: }
7308: }
1.749 raeburn 7309: }
7310: # get lock on access controls for file.
7311: my $lockhash = {
7312: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7313: ':'.$env{'user.domain'},
7314: };
7315: my $tries = 0;
7316: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7317:
7318: while (($gotlock ne 'ok') && $tries <3) {
7319: $tries ++;
7320: sleep 1;
7321: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7322: }
7323: if ($gotlock eq 'ok') {
7324: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7325: my ($tmp)=keys(%curr_permissions);
7326: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7327: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7328: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7329: if (ref($curr_controls) eq 'HASH') {
7330: foreach my $control_item (keys(%{$curr_controls})) {
7331: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7332: if (defined($todelete{$itemnum})) {
7333: push(@deletions,$file_name."\0".$control_item);
7334: } else {
7335: if (defined($changed_items{$itemnum})) {
7336: $new_control{$changed_items{$itemnum}} = $now;
7337: push(@deletions,$file_name."\0".$control_item);
7338: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7339: } else {
7340: $new_control{$control_item} = $$curr_controls{$control_item};
7341: }
7342: }
1.745 raeburn 7343: }
7344: }
7345: }
1.970 raeburn 7346: my ($group);
7347: if (&is_course($domain,$user)) {
7348: ($group,my $file) = split(/\//,$file_name,2);
7349: }
1.749 raeburn 7350: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7351: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7352: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7353: # remove lock
7354: my @del_lock = ($file_name."\0".'locked_access_records');
7355: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7356: my $sqlresult =
1.970 raeburn 7357: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7358: $group);
1.749 raeburn 7359: } else {
7360: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7361: }
1.749 raeburn 7362: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7363: }
7364:
1.827 raeburn 7365: sub make_public_indefinitely {
7366: my ($requrl) = @_;
7367: my $now = time;
7368: my $action = 'activate';
7369: my $aclnum = 0;
7370: if (&is_portfolio_url($requrl)) {
7371: my (undef,$udom,$unum,$file_name,$group) =
7372: &parse_portfolio_url($requrl);
7373: my $current_perms = &get_portfile_permissions($udom,$unum);
7374: my %access_controls = &get_access_controls($current_perms,
7375: $group,$file_name);
7376: foreach my $key (keys(%{$access_controls{$file_name}})) {
7377: my ($num,$scope,$end,$start) =
7378: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7379: if ($scope eq 'public') {
7380: if ($start <= $now && $end == 0) {
7381: $action = 'none';
7382: } else {
7383: $action = 'update';
7384: $aclnum = $num;
7385: }
7386: last;
7387: }
7388: }
7389: if ($action eq 'none') {
7390: return 'ok';
7391: } else {
7392: my %changes;
7393: my $newend = 0;
7394: my $newstart = $now;
7395: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7396: $changes{$action}{$newkey} = {
7397: type => 'public',
7398: time => {
7399: start => $newstart,
7400: end => $newend,
7401: },
7402: };
7403: my ($outcome,$deloutcome,$new_values,$translation) =
7404: &modify_access_controls($file_name,\%changes,$udom,$unum);
7405: return $outcome;
7406: }
7407: } else {
7408: return 'invalid';
7409: }
7410: }
7411:
1.745 raeburn 7412: #------------------------------------------------------Get Marked as Read Only
7413:
7414: sub get_marked_as_readonly {
7415: my ($domain,$user,$what,$group) = @_;
7416: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7417: my @readonly_files;
1.629 banghart 7418: my $cmp1=$what;
7419: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7420: while (my ($file_name,$value) = each(%{$current_permissions})) {
7421: if (defined($group)) {
7422: if ($file_name !~ m-^\Q$group\E/-) {
7423: next;
7424: }
7425: }
1.561 banghart 7426: if (ref($value) eq "ARRAY"){
7427: foreach my $stored_what (@{$value}) {
1.629 banghart 7428: my $cmp2=$stored_what;
1.759 albertel 7429: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7430: $cmp2=join('',@{$stored_what});
1.745 raeburn 7431: }
1.629 banghart 7432: if ($cmp1 eq $cmp2) {
1.561 banghart 7433: push(@readonly_files, $file_name);
1.745 raeburn 7434: last;
1.563 banghart 7435: } elsif (!defined($what)) {
7436: push(@readonly_files, $file_name);
1.745 raeburn 7437: last;
1.561 banghart 7438: }
7439: }
1.745 raeburn 7440: }
1.561 banghart 7441: }
7442: return @readonly_files;
7443: }
1.577 banghart 7444: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7445:
1.577 banghart 7446: sub get_marked_as_readonly_hash {
1.745 raeburn 7447: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7448: my %readonly_files;
1.745 raeburn 7449: while (my ($file_name,$value) = each(%{$current_permissions})) {
7450: if (defined($group)) {
7451: if ($file_name !~ m-^\Q$group\E/-) {
7452: next;
7453: }
7454: }
1.577 banghart 7455: if (ref($value) eq "ARRAY"){
7456: foreach my $stored_what (@{$value}) {
1.745 raeburn 7457: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7458: foreach my $lock_descriptor(@{$stored_what}) {
7459: if ($lock_descriptor eq 'graded') {
7460: $readonly_files{$file_name} = 'graded';
7461: } elsif ($lock_descriptor eq 'handback') {
7462: $readonly_files{$file_name} = 'handback';
7463: } else {
7464: if (!exists($readonly_files{$file_name})) {
7465: $readonly_files{$file_name} = 'locked';
7466: }
7467: }
1.745 raeburn 7468: }
1.750 banghart 7469: }
1.577 banghart 7470: }
7471: }
7472: }
7473: return %readonly_files;
7474: }
1.559 banghart 7475: # ------------------------------------------------------------ Unmark as Read Only
7476:
7477: sub unmark_as_readonly {
1.629 banghart 7478: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7479: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7480: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7481: $file_name = &declutter_portfile($file_name);
1.634 albertel 7482: my $symb_crs = $what;
7483: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7484: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7485: my ($tmp)=keys(%current_permissions);
7486: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7487: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7488: foreach my $file (@readonly_files) {
1.759 albertel 7489: my $clean_file = &declutter_portfile($file);
7490: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7491: my $current_locks = $current_permissions{$file};
1.563 banghart 7492: my @new_locks;
7493: my @del_keys;
7494: if (ref($current_locks) eq "ARRAY"){
7495: foreach my $locker (@{$current_locks}) {
1.632 albertel 7496: my $compare=$locker;
1.749 raeburn 7497: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7498: $compare=join('',@{$locker});
1.746 raeburn 7499: if ($compare ne $symb_crs) {
7500: push(@new_locks, $locker);
7501: }
1.563 banghart 7502: }
7503: }
1.650 albertel 7504: if (scalar(@new_locks) > 0) {
1.563 banghart 7505: $current_permissions{$file} = \@new_locks;
7506: } else {
7507: push(@del_keys, $file);
1.613 albertel 7508: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7509: delete($current_permissions{$file});
1.563 banghart 7510: }
7511: }
1.561 banghart 7512: }
1.613 albertel 7513: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7514: return;
7515: }
1.512 banghart 7516:
1.17 www 7517: # ------------------------------------------------------------ Directory lister
7518:
7519: sub dirlist {
1.955 raeburn 7520: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7521: $uri=~s/^\///;
7522: $uri=~s/\/$//;
1.253 stredwic 7523: my ($udom, $uname);
1.955 raeburn 7524: if ($getuserdir) {
1.253 stredwic 7525: $udom = $userdomain;
7526: $uname = $username;
1.955 raeburn 7527: } else {
7528: (undef,$udom,$uname)=split(/\//,$uri);
7529: if(defined($userdomain)) {
7530: $udom = $userdomain;
7531: }
7532: if(defined($username)) {
7533: $uname = $username;
7534: }
1.253 stredwic 7535: }
1.955 raeburn 7536: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7537:
1.955 raeburn 7538: $dirRoot = $perlvar{'lonDocRoot'};
7539: if (defined($getpropath)) {
7540: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7541: $dirRoot =~ s/\/$//;
1.955 raeburn 7542: } elsif (defined($getuserdir)) {
7543: my $subdir=$uname.'__';
7544: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7545: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7546: ."/$udom/$subdir/$uname";
7547: } elsif (defined($alternateRoot)) {
7548: $dirRoot = $alternateRoot;
1.751 banghart 7549: }
1.253 stredwic 7550:
7551: if($udom) {
7552: if($uname) {
1.955 raeburn 7553: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7554: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7555: .':'.&escape($uname).':'.&escape($udom),
7556: &homeserver($uname,$udom));
7557: if ($listing eq 'unknown_cmd') {
7558: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7559: &homeserver($uname,$udom));
7560: } else {
7561: @listing_results = map { &unescape($_); } split(/:/,$listing);
7562: }
1.605 matthew 7563: if ($listing eq 'unknown_cmd') {
1.800 albertel 7564: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7565: &homeserver($uname,$udom));
1.605 matthew 7566: @listing_results = split(/:/,$listing);
7567: } else {
7568: @listing_results = map { &unescape($_); } split(/:/,$listing);
7569: }
7570: return @listing_results;
1.955 raeburn 7571: } elsif(!$alternateRoot) {
1.800 albertel 7572: my %allusers;
1.841 albertel 7573: my %servers = &get_servers($udom,'library');
1.955 raeburn 7574: foreach my $tryserver (keys(%servers)) {
7575: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7576: &escape($udom),$tryserver);
7577: if ($listing eq 'unknown_cmd') {
7578: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7579: $udom, $tryserver);
7580: } else {
7581: @listing_results = map { &unescape($_); } split(/:/,$listing);
7582: }
1.841 albertel 7583: if ($listing eq 'unknown_cmd') {
7584: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7585: $udom, $tryserver);
7586: @listing_results = split(/:/,$listing);
7587: } else {
7588: @listing_results =
7589: map { &unescape($_); } split(/:/,$listing);
7590: }
7591: if ($listing_results[0] ne 'no_such_dir' &&
7592: $listing_results[0] ne 'empty' &&
7593: $listing_results[0] ne 'con_lost') {
7594: foreach my $line (@listing_results) {
7595: my ($entry) = split(/&/,$line,2);
7596: $allusers{$entry} = 1;
7597: }
7598: }
1.253 stredwic 7599: }
7600: my $alluserstr='';
1.800 albertel 7601: foreach my $user (sort(keys(%allusers))) {
7602: $alluserstr.=$user.'&user:';
1.253 stredwic 7603: }
7604: $alluserstr=~s/:$//;
7605: return split(/:/,$alluserstr);
7606: } else {
1.800 albertel 7607: return ('missing user name');
1.253 stredwic 7608: }
1.955 raeburn 7609: } elsif(!defined($getpropath)) {
1.841 albertel 7610: my @all_domains = sort(&all_domains());
1.955 raeburn 7611: foreach my $domain (@all_domains) {
7612: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7613: }
7614: return @all_domains;
7615: } else {
1.800 albertel 7616: return ('missing domain');
1.275 stredwic 7617: }
7618: }
7619:
7620: # --------------------------------------------- GetFileTimestamp
7621: # This function utilizes dirlist and returns the date stamp for
7622: # when it was last modified. It will also return an error of -1
7623: # if an error occurs
7624:
7625: sub GetFileTimestamp {
1.955 raeburn 7626: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7627: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7628: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7629: my ($fileStat) =
7630: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7631: undef,$getuserdir);
1.275 stredwic 7632: my @stats = split('&', $fileStat);
7633: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7634: # @stats contains first the filename, then the stat output
7635: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7636: } else {
7637: return -1;
1.253 stredwic 7638: }
1.26 www 7639: }
7640:
1.712 albertel 7641: sub stat_file {
7642: my ($uri) = @_;
1.787 albertel 7643: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7644:
1.955 raeburn 7645: my ($udom,$uname,$file);
1.712 albertel 7646: if ($uri =~ m-^/(uploaded|editupload)/-) {
7647: ($udom,$uname,$file) =
1.811 albertel 7648: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7649: $file = 'userfiles/'.$file;
7650: }
7651: if ($uri =~ m-^/res/-) {
7652: ($udom,$uname) =
1.807 albertel 7653: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7654: $file = $uri;
7655: }
7656:
7657: if (!$udom || !$uname || !$file) {
7658: # unable to handle the uri
7659: return ();
7660: }
1.956 raeburn 7661: my $getpropath;
7662: if ($file =~ /^userfiles\//) {
7663: $getpropath = 1;
7664: }
1.955 raeburn 7665: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7666: my @stats = split('&', $result);
1.721 banghart 7667:
1.712 albertel 7668: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7669: shift(@stats); #filename is first
7670: return @stats;
7671: }
7672: return ();
7673: }
7674:
1.26 www 7675: # -------------------------------------------------------- Value of a Condition
7676:
1.713 albertel 7677: # gets the value of a specific preevaluated condition
7678: # stored in the string $env{user.state.<cid>}
7679: # or looks up a condition reference in the bighash and if if hasn't
7680: # already been evaluated recurses into docondval to get the value of
7681: # the condition, then memoizing it to
7682: # $env{user.state.<cid>.<condition>}
1.40 www 7683: sub directcondval {
7684: my $number=shift;
1.620 albertel 7685: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7686: &Apache::lonuserstate::evalstate();
7687: }
1.713 albertel 7688: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7689: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7690: } elsif ($number =~ /^_/) {
7691: my $sub_condition;
7692: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7693: &GDBM_READER(),0640)) {
7694: $sub_condition=$bighash{'conditions'.$number};
7695: untie(%bighash);
7696: }
7697: my $value = &docondval($sub_condition);
1.949 raeburn 7698: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7699: return $value;
7700: }
1.620 albertel 7701: if ($env{'user.state.'.$env{'request.course.id'}}) {
7702: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7703: } else {
7704: return 2;
7705: }
7706: }
7707:
1.713 albertel 7708: # get the collection of conditions for this resource
1.26 www 7709: sub condval {
7710: my $condidx=shift;
1.54 www 7711: my $allpathcond='';
1.713 albertel 7712: foreach my $cond (split(/\|/,$condidx)) {
7713: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7714: $allpathcond.=
7715: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7716: }
1.191 harris41 7717: }
1.54 www 7718: $allpathcond=~s/\|$//;
1.713 albertel 7719: return &docondval($allpathcond);
7720: }
7721:
7722: #evaluates an expression of conditions
7723: sub docondval {
7724: my ($allpathcond) = @_;
7725: my $result=0;
7726: if ($env{'request.course.id'}
7727: && defined($allpathcond)) {
7728: my $operand='|';
7729: my @stack;
7730: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7731: if ($chunk eq '(') {
7732: push @stack,($operand,$result);
7733: } elsif ($chunk eq ')') {
7734: my $before=pop @stack;
7735: if (pop @stack eq '&') {
7736: $result=$result>$before?$before:$result;
7737: } else {
7738: $result=$result>$before?$result:$before;
7739: }
7740: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7741: $operand=$chunk;
7742: } else {
7743: my $new=directcondval($chunk);
7744: if ($operand eq '&') {
7745: $result=$result>$new?$new:$result;
7746: } else {
7747: $result=$result>$new?$result:$new;
7748: }
7749: }
7750: }
1.26 www 7751: }
7752: return $result;
1.421 albertel 7753: }
7754:
7755: # ---------------------------------------------------- Devalidate courseresdata
7756:
7757: sub devalidatecourseresdata {
7758: my ($coursenum,$coursedomain)=@_;
7759: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7760: &devalidate_cache_new('courseres',$hashid);
1.28 www 7761: }
7762:
1.763 www 7763:
1.200 www 7764: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7765: #
7766: # Parameters:
7767: # $coursenum - Number of the course.
7768: # $coursedomain - Domain at which the course was created.
7769: # Returns:
7770: # A hash of the course parameters along (I think) with timestamps
7771: # and version info.
1.877 foxr 7772:
1.624 albertel 7773: sub get_courseresdata {
7774: my ($coursenum,$coursedomain)=@_;
1.200 www 7775: my $coursehom=&homeserver($coursenum,$coursedomain);
7776: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7777: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7778: my %dumpreply;
1.417 albertel 7779: unless (defined($cached)) {
1.624 albertel 7780: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7781: $result=\%dumpreply;
1.251 albertel 7782: my ($tmp) = keys(%dumpreply);
7783: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7784: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7785: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7786: return $tmp;
1.416 albertel 7787: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7788: $result=undef;
1.599 albertel 7789: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7790: }
7791: }
1.624 albertel 7792: return $result;
7793: }
7794:
1.633 albertel 7795: sub devalidateuserresdata {
7796: my ($uname,$udom)=@_;
7797: my $hashid="$udom:$uname";
7798: &devalidate_cache_new('userres',$hashid);
7799: }
7800:
1.624 albertel 7801: sub get_userresdata {
7802: my ($uname,$udom)=@_;
7803: #most student don\'t have any data set, check if there is some data
7804: if (&EXT_cache_status($udom,$uname)) { return undef; }
7805:
7806: my $hashid="$udom:$uname";
7807: my ($result,$cached)=&is_cached_new('userres',$hashid);
7808: if (!defined($cached)) {
7809: my %resourcedata=&dump('resourcedata',$udom,$uname);
7810: $result=\%resourcedata;
7811: &do_cache_new('userres',$hashid,$result,600);
7812: }
7813: my ($tmp)=keys(%$result);
7814: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7815: return $result;
7816: }
7817: #error 2 occurs when the .db doesn't exist
7818: if ($tmp!~/error: 2 /) {
1.672 albertel 7819: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7820: " Trying to get resource data for ".
7821: $uname." at ".$udom.": ".
7822: $tmp."</font>");
7823: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7824: #&EXT_cache_set($udom,$uname);
7825: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7826: undef($tmp); # not really an error so don't send it back
1.624 albertel 7827: }
7828: return $tmp;
7829: }
1.879 foxr 7830: #----------------------------------------------- resdata - return resource data
7831: # Purpose:
7832: # Return resource data for either users or for a course.
7833: # Parameters:
7834: # $name - Course/user name.
7835: # $domain - Name of the domain the user/course is registered on.
7836: # $type - Type of thing $name is (must be 'course' or 'user'
7837: # @which - Array of names of resources desired.
7838: # Returns:
7839: # The value of the first reasource in @which that is found in the
7840: # resource hash.
7841: # Exceptional Conditions:
7842: # If the $type passed in is not valid (not the string 'course' or
7843: # 'user', an undefined reference is returned.
7844: # If none of the resources are found, an undef is returned
1.624 albertel 7845: sub resdata {
7846: my ($name,$domain,$type,@which)=@_;
7847: my $result;
7848: if ($type eq 'course') {
7849: $result=&get_courseresdata($name,$domain);
7850: } elsif ($type eq 'user') {
7851: $result=&get_userresdata($name,$domain);
7852: }
7853: if (!ref($result)) { return $result; }
1.251 albertel 7854: foreach my $item (@which) {
1.927 albertel 7855: if (defined($result->{$item->[0]})) {
7856: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7857: }
1.250 albertel 7858: }
1.291 albertel 7859: return undef;
1.200 www 7860: }
7861:
1.379 matthew 7862: #
7863: # EXT resource caching routines
7864: #
7865:
7866: sub clear_EXT_cache_status {
1.383 albertel 7867: &delenv('cache.EXT.');
1.379 matthew 7868: }
7869:
7870: sub EXT_cache_status {
7871: my ($target_domain,$target_user) = @_;
1.383 albertel 7872: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7873: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7874: # We know already the user has no data
7875: return 1;
7876: } else {
7877: return 0;
7878: }
7879: }
7880:
7881: sub EXT_cache_set {
7882: my ($target_domain,$target_user) = @_;
1.383 albertel 7883: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7884: #&appenv({$cachename => time});
1.379 matthew 7885: }
7886:
1.28 www 7887: # --------------------------------------------------------- Value of a Variable
1.58 www 7888: sub EXT {
1.715 albertel 7889:
1.395 albertel 7890: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7891: unless ($varname) { return ''; }
1.218 albertel 7892: #get real user name/domain, courseid and symb
7893: my $courseid;
1.359 albertel 7894: my $publicuser;
1.427 www 7895: if ($symbparm) {
7896: $symbparm=&get_symb_from_alias($symbparm);
7897: }
1.218 albertel 7898: if (!($uname && $udom)) {
1.790 albertel 7899: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7900: if (!$symbparm) { $symbparm=$cursymb; }
7901: } else {
1.620 albertel 7902: $courseid=$env{'request.course.id'};
1.218 albertel 7903: }
1.48 www 7904: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7905: my $rest;
1.320 albertel 7906: if (defined($therest[0])) {
1.48 www 7907: $rest=join('.',@therest);
7908: } else {
7909: $rest='';
7910: }
1.320 albertel 7911:
1.57 www 7912: my $qualifierrest=$qualifier;
7913: if ($rest) { $qualifierrest.='.'.$rest; }
7914: my $spacequalifierrest=$space;
7915: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7916: if ($realm eq 'user') {
1.48 www 7917: # --------------------------------------------------------------- user.resource
7918: if ($space eq 'resource') {
1.651 albertel 7919: if ( (defined($Apache::lonhomework::parsing_a_problem)
7920: || defined($Apache::lonhomework::parsing_a_task))
7921: &&
1.744 albertel 7922: ($symbparm eq &symbread()) ) {
7923: # if we are in the middle of processing the resource the
7924: # get the value we are planning on committing
7925: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7926: return $Apache::lonhomework::results{$qualifierrest};
7927: } else {
7928: return $Apache::lonhomework::history{$qualifierrest};
7929: }
1.335 albertel 7930: } else {
1.359 albertel 7931: my %restored;
1.620 albertel 7932: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 7933: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7934: } else {
7935: %restored=&restore($symbparm,$courseid,$udom,$uname);
7936: }
1.335 albertel 7937: return $restored{$qualifierrest};
7938: }
1.48 www 7939: # ----------------------------------------------------------------- user.access
7940: } elsif ($space eq 'access') {
1.218 albertel 7941: # FIXME - not supporting calls for a specific user
1.48 www 7942: return &allowed($qualifier,$rest);
7943: # ------------------------------------------ user.preferences, user.environment
7944: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 7945: if (($uname eq $env{'user.name'}) &&
7946: ($udom eq $env{'user.domain'})) {
7947: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 7948: } else {
1.359 albertel 7949: my %returnhash;
7950: if (!$publicuser) {
7951: %returnhash=&userenvironment($udom,$uname,
7952: $qualifierrest);
7953: }
1.218 albertel 7954: return $returnhash{$qualifierrest};
7955: }
1.48 www 7956: # ----------------------------------------------------------------- user.course
7957: } elsif ($space eq 'course') {
1.218 albertel 7958: # FIXME - not supporting calls for a specific user
1.620 albertel 7959: return $env{join('.',('request.course',$qualifier))};
1.48 www 7960: # ------------------------------------------------------------------- user.role
7961: } elsif ($space eq 'role') {
1.218 albertel 7962: # FIXME - not supporting calls for a specific user
1.620 albertel 7963: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 7964: if ($qualifier eq 'value') {
7965: return $role;
7966: } elsif ($qualifier eq 'extent') {
7967: return $where;
7968: }
7969: # ----------------------------------------------------------------- user.domain
7970: } elsif ($space eq 'domain') {
1.218 albertel 7971: return $udom;
1.48 www 7972: # ------------------------------------------------------------------- user.name
7973: } elsif ($space eq 'name') {
1.218 albertel 7974: return $uname;
1.48 www 7975: # ---------------------------------------------------- Any other user namespace
1.29 www 7976: } else {
1.359 albertel 7977: my %reply;
7978: if (!$publicuser) {
7979: %reply=&get($space,[$qualifierrest],$udom,$uname);
7980: }
7981: return $reply{$qualifierrest};
1.48 www 7982: }
1.236 www 7983: } elsif ($realm eq 'query') {
7984: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 7985: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7986: [$spacequalifierrest]);
1.620 albertel 7987: return $env{'form.'.$spacequalifierrest};
1.236 www 7988: } elsif ($realm eq 'request') {
1.48 www 7989: # ------------------------------------------------------------- request.browser
7990: if ($space eq 'browser') {
1.430 www 7991: if ($qualifier eq 'textremote') {
1.676 albertel 7992: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 7993: return 1;
7994: } else {
7995: return 0;
7996: }
7997: } else {
1.620 albertel 7998: return $env{'browser.'.$qualifier};
1.430 www 7999: }
1.57 www 8000: # ------------------------------------------------------------ request.filename
8001: } else {
1.620 albertel 8002: return $env{'request.'.$spacequalifierrest};
1.29 www 8003: }
1.28 www 8004: } elsif ($realm eq 'course') {
1.48 www 8005: # ---------------------------------------------------------- course.description
1.620 albertel 8006: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8007: } elsif ($realm eq 'resource') {
1.165 www 8008:
1.620 albertel 8009: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8010: if (!$symbparm) { $symbparm=&symbread(); }
8011: }
1.693 albertel 8012:
8013: if ($space eq 'title') {
8014: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8015: return &gettitle($symbparm);
8016: }
8017:
8018: if ($space eq 'map') {
8019: my ($map) = &decode_symb($symbparm);
8020: return &symbread($map);
8021: }
1.905 albertel 8022: if ($space eq 'filename') {
8023: if ($symbparm) {
8024: return &clutter((&decode_symb($symbparm))[2]);
8025: }
8026: return &hreflocation('',$env{'request.filename'});
8027: }
1.693 albertel 8028:
8029: my ($section, $group, @groups);
1.593 albertel 8030: my ($courselevelm,$courselevel);
1.539 albertel 8031: if ($symbparm && defined($courseid) &&
1.620 albertel 8032: $courseid eq $env{'request.course.id'}) {
1.165 www 8033:
1.218 albertel 8034: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8035:
1.60 www 8036: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8037: my $symbp=$symbparm;
1.735 albertel 8038: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8039:
8040: my $symbparm=$symbp.'.'.$spacequalifierrest;
8041: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8042:
1.620 albertel 8043: if (($env{'user.name'} eq $uname) &&
8044: ($env{'user.domain'} eq $udom)) {
8045: $section=$env{'request.course.sec'};
1.733 raeburn 8046: @groups = split(/:/,$env{'request.course.groups'});
8047: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8048: } else {
1.539 albertel 8049: if (! defined($usection)) {
1.551 albertel 8050: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8051: } else {
8052: $section = $usection;
8053: }
1.733 raeburn 8054: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8055: }
8056:
8057: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8058: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8059: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8060:
1.593 albertel 8061: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8062: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8063: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8064:
1.60 www 8065: # ----------------------------------------------------------- first, check user
1.624 albertel 8066:
8067: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8068: ([$courselevelr,'resource'],
8069: [$courselevelm,'map' ],
8070: [$courselevel, 'course' ]));
1.931 albertel 8071: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8072:
1.594 albertel 8073: # ------------------------------------------------ second, check some of course
1.684 raeburn 8074: my $coursereply;
1.691 raeburn 8075: if (@groups > 0) {
8076: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8077: $mapparm,$spacequalifierrest);
1.927 albertel 8078: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8079: }
1.96 www 8080:
1.684 raeburn 8081: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8082: $env{'course.'.$courseid.'.domain'},
8083: 'course',
8084: ([$seclevelr, 'resource'],
8085: [$seclevelm, 'map' ],
8086: [$seclevel, 'course' ],
8087: [$courselevelr,'resource']));
8088: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8089:
1.60 www 8090: # ------------------------------------------------------ third, check map parms
1.218 albertel 8091: my %parmhash=();
8092: my $thisparm='';
8093: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8094: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8095: &GDBM_READER(),0640)) {
1.218 albertel 8096: $thisparm=$parmhash{$symbparm};
8097: untie(%parmhash);
8098: }
1.927 albertel 8099: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8100: }
1.594 albertel 8101: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8102:
1.218 albertel 8103: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8104: my $filename;
8105: if (!$symbparm) { $symbparm=&symbread(); }
8106: if ($symbparm) {
1.409 www 8107: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8108: } else {
1.620 albertel 8109: $filename=$env{'request.filename'};
1.282 albertel 8110: }
8111: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8112: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8113: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8114: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8115:
1.927 albertel 8116: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8117: if ($symbparm && defined($courseid) &&
1.620 albertel 8118: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8119: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8120: $env{'course.'.$courseid.'.domain'},
8121: 'course',
1.927 albertel 8122: ([$courselevelm,'map' ],
8123: [$courselevel, 'course']));
8124: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8125: }
1.145 www 8126: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8127: unless ($space eq '0') {
1.336 albertel 8128: my @parts=split(/_/,$space);
8129: my $id=pop(@parts);
8130: my $part=join('_',@parts);
8131: if ($part eq '') { $part='0'; }
1.927 albertel 8132: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8133: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8134: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8135: }
1.395 albertel 8136: if ($recurse) { return undef; }
8137: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8138: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8139: # ---------------------------------------------------- Any other user namespace
8140: } elsif ($realm eq 'environment') {
8141: # ----------------------------------------------------------------- environment
1.620 albertel 8142: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8143: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8144: } else {
1.770 albertel 8145: if ($uname eq 'anonymous' && $udom eq '') {
8146: return '';
8147: }
1.219 albertel 8148: my %returnhash=&userenvironment($udom,$uname,
8149: $spacequalifierrest);
8150: return $returnhash{$spacequalifierrest};
8151: }
1.28 www 8152: } elsif ($realm eq 'system') {
1.48 www 8153: # ----------------------------------------------------------------- system.time
8154: if ($space eq 'time') {
8155: return time;
8156: }
1.696 albertel 8157: } elsif ($realm eq 'server') {
8158: # ----------------------------------------------------------------- system.time
8159: if ($space eq 'name') {
8160: return $ENV{'SERVER_NAME'};
8161: }
1.28 www 8162: }
1.48 www 8163: return '';
1.61 www 8164: }
8165:
1.927 albertel 8166: sub get_reply {
8167: my ($reply_value) = @_;
1.940 raeburn 8168: if (ref($reply_value) eq 'ARRAY') {
8169: if (wantarray) {
8170: return @$reply_value;
8171: }
8172: return $reply_value->[0];
8173: } else {
8174: return $reply_value;
1.927 albertel 8175: }
8176: }
8177:
1.691 raeburn 8178: sub check_group_parms {
8179: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8180: my @groupitems = ();
8181: my $resultitem;
1.927 albertel 8182: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8183: foreach my $group (@{$groups}) {
8184: foreach my $level (@levels) {
1.927 albertel 8185: my $item = $courseid.'.['.$group.'].'.$level->[0];
8186: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8187: }
8188: }
8189: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8190: $env{'course.'.$courseid.'.domain'},
8191: 'course',@groupitems);
8192: return $coursereply;
8193: }
8194:
8195: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8196: my ($courseid,@groups) = @_;
8197: @groups = sort(@groups);
1.691 raeburn 8198: return @groups;
8199: }
8200:
1.395 albertel 8201: sub packages_tab_default {
8202: my ($uri,$varname)=@_;
8203: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8204:
8205: my (@extension,@specifics,$do_default);
8206: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8207: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8208: if ($pack_type eq 'default') {
8209: $do_default=1;
8210: } elsif ($pack_type eq 'extension') {
8211: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8212: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8213: # only look at packages defaults for packages that this id is
1.738 albertel 8214: push(@specifics,[$package,$pack_type,$pack_part]);
8215: }
8216: }
8217: # first look for a package that matches the requested part id
8218: foreach my $package (@specifics) {
8219: my (undef,$pack_type,$pack_part)=@{$package};
8220: next if ($pack_part ne $part);
8221: if (defined($packagetab{"$pack_type&$name&default"})) {
8222: return $packagetab{"$pack_type&$name&default"};
8223: }
8224: }
8225: # look for any possible matching non extension_ package
8226: foreach my $package (@specifics) {
8227: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8228: if (defined($packagetab{"$pack_type&$name&default"})) {
8229: return $packagetab{"$pack_type&$name&default"};
8230: }
1.585 albertel 8231: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8232: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8233: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8234: }
8235: }
1.738 albertel 8236: # look for any posible extension_ match
8237: foreach my $package (@extension) {
8238: my ($package,$pack_type)=@{$package};
8239: if (defined($packagetab{"$pack_type&$name&default"})) {
8240: return $packagetab{"$pack_type&$name&default"};
8241: }
8242: if (defined($packagetab{$package."&$name&default"})) {
8243: return $packagetab{$package."&$name&default"};
8244: }
8245: }
8246: # look for a global default setting
8247: if ($do_default && defined($packagetab{"default&$name&default"})) {
8248: return $packagetab{"default&$name&default"};
8249: }
1.395 albertel 8250: return undef;
8251: }
8252:
1.334 albertel 8253: sub add_prefix_and_part {
8254: my ($prefix,$part)=@_;
8255: my $keyroot;
8256: if (defined($prefix) && $prefix !~ /^__/) {
8257: # prefix that has a part already
8258: $keyroot=$prefix;
8259: } elsif (defined($prefix)) {
8260: # prefix that is missing a part
8261: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8262: } else {
8263: # no prefix at all
8264: if (defined($part)) { $keyroot='_'.$part; }
8265: }
8266: return $keyroot;
8267: }
8268:
1.71 www 8269: # ---------------------------------------------------------------- Get metadata
8270:
1.599 albertel 8271: my %metaentry;
1.71 www 8272: sub metadata {
1.176 www 8273: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8274: $uri=&declutter($uri);
1.288 albertel 8275: # if it is a non metadata possible uri return quickly
1.529 albertel 8276: if (($uri eq '') ||
8277: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8278: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8279: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8280: return undef;
8281: }
8282: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8283: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8284: return undef;
1.288 albertel 8285: }
1.73 www 8286: my $filename=$uri;
8287: $uri=~s/\.meta$//;
1.172 www 8288: #
8289: # Is the metadata already cached?
1.177 www 8290: # Look at timestamp of caching
1.172 www 8291: # Everything is cached by the main uri, libraries are never directly cached
8292: #
1.428 albertel 8293: if (!defined($liburi)) {
1.599 albertel 8294: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8295: if (defined($cached)) { return $result->{':'.$what}; }
8296: }
8297: {
1.172 www 8298: #
8299: # Is this a recursive call for a library?
8300: #
1.599 albertel 8301: # if (! exists($metacache{$uri})) {
8302: # $metacache{$uri}={};
8303: # }
1.924 albertel 8304: my $cachetime = 60*60;
1.171 www 8305: if ($liburi) {
8306: $liburi=&declutter($liburi);
8307: $filename=$liburi;
1.401 bowersj2 8308: } else {
1.599 albertel 8309: &devalidate_cache_new('meta',$uri);
8310: undef(%metaentry);
1.401 bowersj2 8311: }
1.140 www 8312: my %metathesekeys=();
1.73 www 8313: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8314: my $metastring;
1.924 albertel 8315: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8316: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8317: $metastring =
1.929 albertel 8318: &Apache::lonnet::ssi_body($which,
1.924 albertel 8319: ('grade_target' => 'meta'));
8320: $cachetime = 1; # only want this cached in the child not long term
8321: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8322: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8323: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8324: $metastring=&getfile($file);
1.489 albertel 8325: }
1.208 albertel 8326: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8327: my $token;
1.140 www 8328: undef %metathesekeys;
1.71 www 8329: while ($token=$parser->get_token) {
1.339 albertel 8330: if ($token->[0] eq 'S') {
8331: if (defined($token->[2]->{'package'})) {
1.172 www 8332: #
8333: # This is a package - get package info
8334: #
1.339 albertel 8335: my $package=$token->[2]->{'package'};
8336: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8337: if (defined($token->[2]->{'id'})) {
8338: $keyroot.='_'.$token->[2]->{'id'};
8339: }
1.599 albertel 8340: if ($metaentry{':packages'}) {
8341: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8342: } else {
1.599 albertel 8343: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8344: }
1.736 albertel 8345: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8346: my $part=$keyroot;
8347: $part=~s/^\_//;
1.736 albertel 8348: if ($pack_entry=~/^\Q$package\E\&/ ||
8349: $pack_entry=~/^\Q$package\E_0\&/) {
8350: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8351: # ignore package.tab specified default values
8352: # here &package_tab_default() will fetch those
8353: if ($subp eq 'default') { next; }
1.736 albertel 8354: my $value=$packagetab{$pack_entry};
1.432 albertel 8355: my $unikey;
8356: if ($pack =~ /_0$/) {
8357: $unikey='parameter_0_'.$name;
8358: $part=0;
8359: } else {
8360: $unikey='parameter'.$keyroot.'_'.$name;
8361: }
1.339 albertel 8362: if ($subp eq 'display') {
8363: $value.=' [Part: '.$part.']';
8364: }
1.599 albertel 8365: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8366: $metathesekeys{$unikey}=1;
1.599 albertel 8367: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8368: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8369: }
1.599 albertel 8370: if (defined($metaentry{':'.$unikey.'.default'})) {
8371: $metaentry{':'.$unikey}=
8372: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8373: }
1.339 albertel 8374: }
8375: }
8376: } else {
1.172 www 8377: #
8378: # This is not a package - some other kind of start tag
1.339 albertel 8379: #
8380: my $entry=$token->[1];
8381: my $unikey;
8382: if ($entry eq 'import') {
8383: $unikey='';
8384: } else {
8385: $unikey=$entry;
8386: }
8387: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8388:
8389: if (defined($token->[2]->{'id'})) {
8390: $unikey.='_'.$token->[2]->{'id'};
8391: }
1.175 www 8392:
1.339 albertel 8393: if ($entry eq 'import') {
1.175 www 8394: #
8395: # Importing a library here
1.339 albertel 8396: #
8397: if ($depthcount<20) {
8398: my $location=$parser->get_text('/import');
8399: my $dir=$filename;
8400: $dir=~s|[^/]*$||;
8401: $location=&filelocation($dir,$location);
1.736 albertel 8402: my $metadata =
8403: &metadata($uri,'keys', $location,$unikey,
8404: $depthcount+1);
8405: foreach my $meta (split(',',$metadata)) {
8406: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8407: $metathesekeys{$meta}=1;
1.339 albertel 8408: }
8409: }
8410: } else {
8411:
8412: if (defined($token->[2]->{'name'})) {
8413: $unikey.='_'.$token->[2]->{'name'};
8414: }
8415: $metathesekeys{$unikey}=1;
1.736 albertel 8416: foreach my $param (@{$token->[3]}) {
8417: $metaentry{':'.$unikey.'.'.$param} =
8418: $token->[2]->{$param};
1.339 albertel 8419: }
8420: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8421: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8422: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8423: # only ws inside the tag, and not in default, so use default
8424: # as value
1.599 albertel 8425: $metaentry{':'.$unikey}=$default;
1.908 albertel 8426: } elsif ( $internaltext =~ /\S/ ) {
8427: # something interesting inside the tag
8428: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8429: } else {
1.908 albertel 8430: # no interesting values, don't set a default
1.339 albertel 8431: }
1.172 www 8432: # end of not-a-package not-a-library import
1.339 albertel 8433: }
1.172 www 8434: # end of not-a-package start tag
1.339 albertel 8435: }
1.172 www 8436: # the next is the end of "start tag"
1.339 albertel 8437: }
8438: }
1.483 albertel 8439: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8440: $extension = lc($extension);
8441: if ($extension eq 'htm') { $extension='html'; }
8442:
1.737 albertel 8443: foreach my $key (keys(%packagetab)) {
1.483 albertel 8444: #no specific packages #how's our extension
8445: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8446: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8447: \%metathesekeys);
8448: }
1.883 albertel 8449:
8450: if (!exists($metaentry{':packages'})
8451: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8452: foreach my $key (keys(%packagetab)) {
1.483 albertel 8453: #no specific packages well let's get default then
8454: if ($key!~/^default&/) { next; }
1.488 albertel 8455: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8456: \%metathesekeys);
8457: }
8458: }
1.338 www 8459: # are there custom rights to evaluate
1.599 albertel 8460: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8461:
1.338 www 8462: #
8463: # Importing a rights file here
1.339 albertel 8464: #
8465: unless ($depthcount) {
1.599 albertel 8466: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8467: my $dir=$filename;
8468: $dir=~s|[^/]*$||;
8469: $location=&filelocation($dir,$location);
1.736 albertel 8470: my $rights_metadata =
8471: &metadata($uri,'keys',$location,'_rights',
8472: $depthcount+1);
8473: foreach my $rights (split(',',$rights_metadata)) {
8474: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8475: $metathesekeys{$rights}=1;
1.339 albertel 8476: }
8477: }
8478: }
1.737 albertel 8479: # uniqifiy package listing
8480: my %seen;
8481: my @uniq_packages =
8482: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8483: $metaentry{':packages'} = join(',',@uniq_packages);
8484:
8485: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8486: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8487: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8488: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8489: # this is the end of "was not already recently cached
1.71 www 8490: }
1.599 albertel 8491: return $metaentry{':'.$what};
1.261 albertel 8492: }
8493:
1.488 albertel 8494: sub metadata_create_package_def {
1.483 albertel 8495: my ($uri,$key,$package,$metathesekeys)=@_;
8496: my ($pack,$name,$subp)=split(/\&/,$key);
8497: if ($subp eq 'default') { next; }
8498:
1.599 albertel 8499: if (defined($metaentry{':packages'})) {
8500: $metaentry{':packages'}.=','.$package;
1.483 albertel 8501: } else {
1.599 albertel 8502: $metaentry{':packages'}=$package;
1.483 albertel 8503: }
8504: my $value=$packagetab{$key};
8505: my $unikey;
8506: $unikey='parameter_0_'.$name;
1.599 albertel 8507: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8508: $$metathesekeys{$unikey}=1;
1.599 albertel 8509: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8510: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8511: }
1.599 albertel 8512: if (defined($metaentry{':'.$unikey.'.default'})) {
8513: $metaentry{':'.$unikey}=
8514: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8515: }
8516: }
8517:
1.261 albertel 8518: sub metadata_generate_part0 {
8519: my ($metadata,$metacache,$uri) = @_;
8520: my %allnames;
1.737 albertel 8521: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8522: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8523: my $part=$$metacache{':'.$metakey.'.part'};
8524: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8525: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8526: $allnames{$name}=$part;
8527: }
8528: }
8529: }
8530: foreach my $name (keys(%allnames)) {
8531: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8532: my $key=":parameter_0_$name";
1.261 albertel 8533: $$metacache{"$key.part"}='0';
8534: $$metacache{"$key.name"}=$name;
1.428 albertel 8535: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8536: $allnames{$name}.'_'.$name.
8537: '.type'};
1.428 albertel 8538: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8539: '.display'};
1.644 www 8540: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8541: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8542: $$metacache{"$key.display"}=$olddis;
8543: }
1.71 www 8544: }
8545:
1.764 albertel 8546: # ------------------------------------------------------ Devalidate title cache
8547:
8548: sub devalidate_title_cache {
8549: my ($url)=@_;
8550: if (!$env{'request.course.id'}) { return; }
8551: my $symb=&symbread($url);
8552: if (!$symb) { return; }
8553: my $key=$env{'request.course.id'}."\0".$symb;
8554: &devalidate_cache_new('title',$key);
8555: }
8556:
1.1014 droeschl 8557: # ------------------------------------------------- Get the title of a course
8558:
8559: sub current_course_title {
8560: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8561: }
1.301 www 8562: # ------------------------------------------------- Get the title of a resource
8563:
8564: sub gettitle {
8565: my $urlsymb=shift;
8566: my $symb=&symbread($urlsymb);
1.534 albertel 8567: if ($symb) {
1.620 albertel 8568: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8569: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8570: if (defined($cached)) {
8571: return $result;
8572: }
1.534 albertel 8573: my ($map,$resid,$url)=&decode_symb($symb);
8574: my $title='';
1.907 albertel 8575: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8576: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8577: } else {
8578: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8579: &GDBM_READER(),0640)) {
8580: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8581: $title=$bighash{'title_'.$mapid.'.'.$resid};
8582: untie(%bighash);
8583: }
1.534 albertel 8584: }
8585: $title=~s/\&colon\;/\:/gs;
8586: if ($title) {
1.599 albertel 8587: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8588: }
8589: $urlsymb=$url;
8590: }
8591: my $title=&metadata($urlsymb,'title');
8592: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8593: return $title;
1.301 www 8594: }
1.613 albertel 8595:
1.614 albertel 8596: sub get_slot {
8597: my ($which,$cnum,$cdom)=@_;
8598: if (!$cnum || !$cdom) {
1.790 albertel 8599: (undef,my $courseid)=&whichuser();
1.620 albertel 8600: $cdom=$env{'course.'.$courseid.'.domain'};
8601: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8602: }
1.703 albertel 8603: my $key=join("\0",'slots',$cdom,$cnum,$which);
8604: my %slotinfo;
8605: if (exists($remembered{$key})) {
8606: $slotinfo{$which} = $remembered{$key};
8607: } else {
8608: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8609: &Apache::lonhomework::showhash(%slotinfo);
8610: my ($tmp)=keys(%slotinfo);
8611: if ($tmp=~/^error:/) { return (); }
8612: $remembered{$key} = $slotinfo{$which};
8613: }
1.616 albertel 8614: if (ref($slotinfo{$which}) eq 'HASH') {
8615: return %{$slotinfo{$which}};
8616: }
8617: return $slotinfo{$which};
1.614 albertel 8618: }
1.31 www 8619: # ------------------------------------------------- Update symbolic store links
8620:
8621: sub symblist {
8622: my ($mapname,%newhash)=@_;
1.438 www 8623: $mapname=&deversion(&declutter($mapname));
1.31 www 8624: my %hash;
1.620 albertel 8625: if (($env{'request.course.fn'}) && (%newhash)) {
8626: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8627: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8628: foreach my $url (keys(%newhash)) {
1.711 albertel 8629: next if ($url eq 'last_known'
8630: && $env{'form.no_update_last_known'});
8631: $hash{declutter($url)}=&encode_symb($mapname,
8632: $newhash{$url}->[1],
8633: $newhash{$url}->[0]);
1.191 harris41 8634: }
1.31 www 8635: if (untie(%hash)) {
8636: return 'ok';
8637: }
8638: }
8639: }
8640: return 'error';
1.212 www 8641: }
8642:
8643: # --------------------------------------------------------------- Verify a symb
8644:
8645: sub symbverify {
1.510 www 8646: my ($symb,$thisurl)=@_;
8647: my $thisfn=$thisurl;
1.439 www 8648: $thisfn=&declutter($thisfn);
1.215 www 8649: # direct jump to resource in page or to a sequence - will construct own symbs
8650: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8651: # check URL part
1.409 www 8652: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8653:
1.431 www 8654: unless ($url eq $thisfn) { return 0; }
1.213 www 8655:
1.216 www 8656: $symb=&symbclean($symb);
1.510 www 8657: $thisurl=&deversion($thisurl);
1.439 www 8658: $thisfn=&deversion($thisfn);
1.213 www 8659:
8660: my %bighash;
8661: my $okay=0;
1.431 www 8662:
1.620 albertel 8663: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8664: &GDBM_READER(),0640)) {
1.1032 raeburn 8665: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8666: $thisurl =~ s/\?.+$//;
8667: }
1.510 www 8668: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8669: unless ($ids) {
1.510 www 8670: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8671: }
8672: if ($ids) {
8673: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8674: foreach my $id (split(/\,/,$ids)) {
8675: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8676: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8677: $symb =~ s/\?.+$//;
8678: }
1.216 www 8679: if (
8680: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8681: eq $symb) {
1.620 albertel 8682: if (($env{'request.role.adv'}) ||
1.800 albertel 8683: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8684: $okay=1;
8685: }
8686: }
1.216 www 8687: }
8688: }
1.213 www 8689: untie(%bighash);
8690: }
8691: return $okay;
1.31 www 8692: }
8693:
1.210 www 8694: # --------------------------------------------------------------- Clean-up symb
8695:
8696: sub symbclean {
8697: my $symb=shift;
1.568 albertel 8698: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8699: # remove version from map
8700: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8701:
1.210 www 8702: # remove version from URL
8703: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8704:
1.507 www 8705: # remove wrapper
8706:
1.510 www 8707: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8708: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8709: return $symb;
1.409 www 8710: }
8711:
8712: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8713:
8714: sub encode_symb {
8715: my ($map,$resid,$url)=@_;
8716: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8717: }
1.409 www 8718:
8719: sub decode_symb {
1.568 albertel 8720: my $symb=shift;
8721: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8722: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8723: return (&fixversion($map),$resid,&fixversion($url));
8724: }
8725:
8726: sub fixversion {
8727: my $fn=shift;
1.609 banghart 8728: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8729: my %bighash;
8730: my $uri=&clutter($fn);
1.620 albertel 8731: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8732: # is this cached?
1.599 albertel 8733: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8734: if (defined($cached)) { return $result; }
8735: # unfortunately not cached, or expired
1.620 albertel 8736: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8737: &GDBM_READER(),0640)) {
8738: if ($bighash{'version_'.$uri}) {
8739: my $version=$bighash{'version_'.$uri};
1.444 www 8740: unless (($version eq 'mostrecent') ||
8741: ($version==&getversion($uri))) {
1.440 www 8742: $uri=~s/\.(\w+)$/\.$version\.$1/;
8743: }
8744: }
8745: untie %bighash;
1.413 www 8746: }
1.599 albertel 8747: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8748: }
8749:
8750: sub deversion {
8751: my $url=shift;
8752: $url=~s/\.\d+\.(\w+)$/\.$1/;
8753: return $url;
1.210 www 8754: }
8755:
1.31 www 8756: # ------------------------------------------------------ Return symb list entry
8757:
8758: sub symbread {
1.249 www 8759: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8760: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8761: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8762: # no filename provided? try from environment
1.44 www 8763: unless ($thisfn) {
1.620 albertel 8764: if ($env{'request.symb'}) {
8765: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8766: }
1.620 albertel 8767: $thisfn=$env{'request.filename'};
1.44 www 8768: }
1.569 albertel 8769: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8770: # is that filename actually a symb? Verify, clean, and return
8771: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8772: if (&symbverify($thisfn,$1)) {
1.620 albertel 8773: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8774: }
1.242 www 8775: }
1.44 www 8776: $thisfn=declutter($thisfn);
1.31 www 8777: my %hash;
1.37 www 8778: my %bighash;
8779: my $syval='';
1.620 albertel 8780: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8781: my $targetfn = $thisfn;
1.609 banghart 8782: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8783: $targetfn = 'adm/wrapper/'.$thisfn;
8784: }
1.687 albertel 8785: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8786: $targetfn=$1;
8787: }
1.620 albertel 8788: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8789: &GDBM_READER(),0640)) {
1.481 raeburn 8790: $syval=$hash{$targetfn};
1.37 www 8791: untie(%hash);
8792: }
8793: # ---------------------------------------------------------- There was an entry
8794: if ($syval) {
1.601 albertel 8795: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8796: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8797: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8798: #return $env{$cache_str}='';
1.601 albertel 8799: #}
8800: #$syval.=$1;
8801: #}
1.37 www 8802: } else {
8803: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8804: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8805: &GDBM_READER(),0640)) {
1.37 www 8806: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8807: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8808: unless ($ids) {
8809: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8810: }
8811: unless ($ids) {
8812: # alias?
8813: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8814: }
1.37 www 8815: if ($ids) {
8816: # ------------------------------------------------------------------- Has ID(s)
8817: my @possibilities=split(/\,/,$ids);
1.39 www 8818: if ($#possibilities==0) {
8819: # ----------------------------------------------- There is only one possibility
1.37 www 8820: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8821: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8822: $resid,$thisfn);
1.249 www 8823: } elsif (!$donotrecurse) {
1.39 www 8824: # ------------------------------------------ There is more than one possibility
8825: my $realpossible=0;
1.800 albertel 8826: foreach my $id (@possibilities) {
8827: my $file=$bighash{'src_'.$id};
1.39 www 8828: if (&allowed('bre',$file)) {
1.800 albertel 8829: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8830: if ($bighash{'map_type_'.$mapid} ne 'page') {
8831: $realpossible++;
1.626 albertel 8832: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8833: $resid,$thisfn);
1.39 www 8834: }
8835: }
1.191 harris41 8836: }
1.39 www 8837: if ($realpossible!=1) { $syval=''; }
1.249 www 8838: } else {
8839: $syval='';
1.37 www 8840: }
8841: }
8842: untie(%bighash)
1.481 raeburn 8843: }
1.31 www 8844: }
1.62 www 8845: if ($syval) {
1.620 albertel 8846: return $env{$cache_str}=$syval;
1.62 www 8847: }
1.31 www 8848: }
1.949 raeburn 8849: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8850: return $env{$cache_str}='';
1.31 www 8851: }
8852:
8853: # ---------------------------------------------------------- Return random seed
8854:
1.32 www 8855: sub numval {
8856: my $txt=shift;
8857: $txt=~tr/A-J/0-9/;
8858: $txt=~tr/a-j/0-9/;
8859: $txt=~tr/K-T/0-9/;
8860: $txt=~tr/k-t/0-9/;
8861: $txt=~tr/U-Z/0-5/;
8862: $txt=~tr/u-z/0-5/;
8863: $txt=~s/\D//g;
1.564 albertel 8864: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8865: return int($txt);
1.368 albertel 8866: }
8867:
1.484 albertel 8868: sub numval2 {
8869: my $txt=shift;
8870: $txt=~tr/A-J/0-9/;
8871: $txt=~tr/a-j/0-9/;
8872: $txt=~tr/K-T/0-9/;
8873: $txt=~tr/k-t/0-9/;
8874: $txt=~tr/U-Z/0-5/;
8875: $txt=~tr/u-z/0-5/;
8876: $txt=~s/\D//g;
8877: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8878: my $total;
8879: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8880: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 8881: return int($total);
8882: }
8883:
1.575 albertel 8884: sub numval3 {
8885: use integer;
8886: my $txt=shift;
8887: $txt=~tr/A-J/0-9/;
8888: $txt=~tr/a-j/0-9/;
8889: $txt=~tr/K-T/0-9/;
8890: $txt=~tr/k-t/0-9/;
8891: $txt=~tr/U-Z/0-5/;
8892: $txt=~tr/u-z/0-5/;
8893: $txt=~s/\D//g;
8894: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8895: my $total;
8896: foreach my $val (@txts) { $total+=$val; }
8897: if ($_64bit) { $total=(($total<<32)>>32); }
8898: return $total;
8899: }
8900:
1.675 albertel 8901: sub digest {
8902: my ($data)=@_;
8903: my $digest=&Digest::MD5::md5($data);
8904: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8905: my ($e,$f);
8906: {
8907: use integer;
8908: $e=($a+$b);
8909: $f=($c+$d);
8910: if ($_64bit) {
8911: $e=(($e<<32)>>32);
8912: $f=(($f<<32)>>32);
8913: }
8914: }
8915: if (wantarray) {
8916: return ($e,$f);
8917: } else {
8918: my $g;
8919: {
8920: use integer;
8921: $g=($e+$f);
8922: if ($_64bit) {
8923: $g=(($g<<32)>>32);
8924: }
8925: }
8926: return $g;
8927: }
8928: }
8929:
1.368 albertel 8930: sub latest_rnd_algorithm_id {
1.675 albertel 8931: return '64bit5';
1.366 albertel 8932: }
1.32 www 8933:
1.503 albertel 8934: sub get_rand_alg {
8935: my ($courseid)=@_;
1.790 albertel 8936: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 8937: if ($courseid) {
1.620 albertel 8938: return $env{"course.$courseid.rndseed"};
1.503 albertel 8939: }
8940: return &latest_rnd_algorithm_id();
8941: }
8942:
1.562 albertel 8943: sub validCODE {
8944: my ($CODE)=@_;
8945: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8946: return 0;
8947: }
8948:
1.491 albertel 8949: sub getCODE {
1.620 albertel 8950: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 8951: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8952: defined($Apache::lonhomework::parsing_a_task) ) &&
8953: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 8954: return $Apache::lonhomework::history{'resource.CODE'};
8955: }
8956: return undef;
8957: }
8958:
1.31 www 8959: sub rndseed {
1.155 albertel 8960: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 8961: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 8962: if (!defined($symb)) {
1.366 albertel 8963: unless ($symb=$wsymb) { return time; }
8964: }
8965: if (!$courseid) { $courseid=$wcourseid; }
8966: if (!$domain) { $domain=$wdomain; }
8967: if (!$username) { $username=$wusername }
1.503 albertel 8968: my $which=&get_rand_alg();
1.803 albertel 8969:
1.491 albertel 8970: if (defined(&getCODE())) {
1.675 albertel 8971: if ($which eq '64bit5') {
8972: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8973: } elsif ($which eq '64bit4') {
1.575 albertel 8974: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8975: } else {
8976: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8977: }
1.675 albertel 8978: } elsif ($which eq '64bit5') {
8979: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 8980: } elsif ($which eq '64bit4') {
8981: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 8982: } elsif ($which eq '64bit3') {
8983: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 8984: } elsif ($which eq '64bit2') {
8985: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 8986: } elsif ($which eq '64bit') {
8987: return &rndseed_64bit($symb,$courseid,$domain,$username);
8988: }
8989: return &rndseed_32bit($symb,$courseid,$domain,$username);
8990: }
8991:
8992: sub rndseed_32bit {
8993: my ($symb,$courseid,$domain,$username)=@_;
8994: {
8995: use integer;
8996: my $symbchck=unpack("%32C*",$symb) << 27;
8997: my $symbseed=numval($symb) << 22;
8998: my $namechck=unpack("%32C*",$username) << 17;
8999: my $nameseed=numval($username) << 12;
9000: my $domainseed=unpack("%32C*",$domain) << 7;
9001: my $courseseed=unpack("%32C*",$courseid);
9002: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9003: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9004: #&logthis("rndseed :$num:$symb");
1.564 albertel 9005: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9006: return $num;
9007: }
9008: }
9009:
9010: sub rndseed_64bit {
9011: my ($symb,$courseid,$domain,$username)=@_;
9012: {
9013: use integer;
9014: my $symbchck=unpack("%32S*",$symb) << 21;
9015: my $symbseed=numval($symb) << 10;
9016: my $namechck=unpack("%32S*",$username);
9017:
9018: my $nameseed=numval($username) << 21;
9019: my $domainseed=unpack("%32S*",$domain) << 10;
9020: my $courseseed=unpack("%32S*",$courseid);
9021:
9022: my $num1=$symbchck+$symbseed+$namechck;
9023: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9024: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9025: #&logthis("rndseed :$num:$symb");
1.564 albertel 9026: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9027: return "$num1,$num2";
1.155 albertel 9028: }
1.366 albertel 9029: }
9030:
1.443 albertel 9031: sub rndseed_64bit2 {
9032: my ($symb,$courseid,$domain,$username)=@_;
9033: {
9034: use integer;
9035: # strings need to be an even # of cahracters long, it it is odd the
9036: # last characters gets thrown away
9037: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9038: my $symbseed=numval($symb) << 10;
9039: my $namechck=unpack("%32S*",$username.' ');
9040:
9041: my $nameseed=numval($username) << 21;
1.501 albertel 9042: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9043: my $courseseed=unpack("%32S*",$courseid.' ');
9044:
9045: my $num1=$symbchck+$symbseed+$namechck;
9046: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9047: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9048: #&logthis("rndseed :$num:$symb");
1.803 albertel 9049: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9050: return "$num1,$num2";
9051: }
9052: }
9053:
9054: sub rndseed_64bit3 {
9055: my ($symb,$courseid,$domain,$username)=@_;
9056: {
9057: use integer;
9058: # strings need to be an even # of cahracters long, it it is odd the
9059: # last characters gets thrown away
9060: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9061: my $symbseed=numval2($symb) << 10;
9062: my $namechck=unpack("%32S*",$username.' ');
9063:
9064: my $nameseed=numval2($username) << 21;
1.443 albertel 9065: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9066: my $courseseed=unpack("%32S*",$courseid.' ');
9067:
9068: my $num1=$symbchck+$symbseed+$namechck;
9069: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9070: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9071: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9072: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9073:
1.503 albertel 9074: return "$num1:$num2";
1.443 albertel 9075: }
9076: }
9077:
1.575 albertel 9078: sub rndseed_64bit4 {
9079: my ($symb,$courseid,$domain,$username)=@_;
9080: {
9081: use integer;
9082: # strings need to be an even # of cahracters long, it it is odd the
9083: # last characters gets thrown away
9084: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9085: my $symbseed=numval3($symb) << 10;
9086: my $namechck=unpack("%32S*",$username.' ');
9087:
9088: my $nameseed=numval3($username) << 21;
9089: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9090: my $courseseed=unpack("%32S*",$courseid.' ');
9091:
9092: my $num1=$symbchck+$symbseed+$namechck;
9093: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9094: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9095: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9096: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9097:
9098: return "$num1:$num2";
9099: }
9100: }
9101:
1.675 albertel 9102: sub rndseed_64bit5 {
9103: my ($symb,$courseid,$domain,$username)=@_;
9104: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9105: return "$num1:$num2";
9106: }
9107:
1.366 albertel 9108: sub rndseed_CODE_64bit {
9109: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9110: {
1.366 albertel 9111: use integer;
1.443 albertel 9112: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9113: my $symbseed=numval2($symb);
1.491 albertel 9114: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9115: my $CODEseed=numval(&getCODE());
1.443 albertel 9116: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9117: my $num1=$symbseed+$CODEchck;
9118: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9119: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9120: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9121: if ($_64bit) { $num1=(($num1<<32)>>32); }
9122: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9123: return "$num1:$num2";
1.366 albertel 9124: }
9125: }
9126:
1.575 albertel 9127: sub rndseed_CODE_64bit4 {
9128: my ($symb,$courseid,$domain,$username)=@_;
9129: {
9130: use integer;
9131: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9132: my $symbseed=numval3($symb);
9133: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9134: my $CODEseed=numval3(&getCODE());
9135: my $courseseed=unpack("%32S*",$courseid.' ');
9136: my $num1=$symbseed+$CODEchck;
9137: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9138: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9139: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9140: if ($_64bit) { $num1=(($num1<<32)>>32); }
9141: if ($_64bit) { $num2=(($num2<<32)>>32); }
9142: return "$num1:$num2";
9143: }
9144: }
9145:
1.675 albertel 9146: sub rndseed_CODE_64bit5 {
9147: my ($symb,$courseid,$domain,$username)=@_;
9148: my $code = &getCODE();
9149: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9150: return "$num1:$num2";
9151: }
9152:
1.366 albertel 9153: sub setup_random_from_rndseed {
9154: my ($rndseed)=@_;
1.503 albertel 9155: if ($rndseed =~/([,:])/) {
9156: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9157: &Math::Random::random_set_seed(abs($num1),abs($num2));
9158: } else {
9159: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9160: }
1.36 albertel 9161: }
9162:
1.474 albertel 9163: sub latest_receipt_algorithm_id {
1.835 albertel 9164: return 'receipt3';
1.474 albertel 9165: }
9166:
1.480 www 9167: sub recunique {
9168: my $fucourseid=shift;
9169: my $unique;
1.835 albertel 9170: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9171: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9172: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9173: } else {
9174: $unique=$perlvar{'lonReceipt'};
9175: }
9176: return unpack("%32C*",$unique);
9177: }
9178:
9179: sub recprefix {
9180: my $fucourseid=shift;
9181: my $prefix;
1.835 albertel 9182: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9183: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9184: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9185: } else {
9186: $prefix=$perlvar{'lonHostID'};
9187: }
9188: return unpack("%32C*",$prefix);
9189: }
9190:
1.76 www 9191: sub ireceipt {
1.474 albertel 9192: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9193:
9194: my $return =&recprefix($fucourseid).'-';
9195:
9196: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9197: $env{'request.state'} eq 'construct') {
9198: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9199: return $return;
9200: }
9201:
1.76 www 9202: my $cuname=unpack("%32C*",$funame);
9203: my $cudom=unpack("%32C*",$fudom);
9204: my $cucourseid=unpack("%32C*",$fucourseid);
9205: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9206: my $cunique=&recunique($fucourseid);
1.474 albertel 9207: my $cpart=unpack("%32S*",$part);
1.835 albertel 9208: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9209:
1.790 albertel 9210: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9211:
9212: $return.= ($cunique%$cuname+
9213: $cunique%$cudom+
9214: $cusymb%$cuname+
9215: $cusymb%$cudom+
9216: $cucourseid%$cuname+
9217: $cucourseid%$cudom+
9218: $cpart%$cuname+
9219: $cpart%$cudom);
9220: } else {
9221: $return.= ($cunique%$cuname+
9222: $cunique%$cudom+
9223: $cusymb%$cuname+
9224: $cusymb%$cudom+
9225: $cucourseid%$cuname+
9226: $cucourseid%$cudom);
9227: }
9228: return $return;
1.76 www 9229: }
9230:
9231: sub receipt {
1.474 albertel 9232: my ($part)=@_;
1.790 albertel 9233: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9234: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9235: }
1.260 ng 9236:
1.790 albertel 9237: sub whichuser {
9238: my ($passedsymb)=@_;
9239: my ($symb,$courseid,$domain,$name,$publicuser);
9240: if (defined($env{'form.grade_symb'})) {
9241: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9242: my $allowed=&allowed('vgr',$tmp_courseid);
9243: if (!$allowed &&
9244: exists($env{'request.course.sec'}) &&
9245: $env{'request.course.sec'} !~ /^\s*$/) {
9246: $allowed=&allowed('vgr',$tmp_courseid.
9247: '/'.$env{'request.course.sec'});
9248: }
9249: if ($allowed) {
9250: ($symb)=&get_env_multiple('form.grade_symb');
9251: $courseid=$tmp_courseid;
9252: ($domain)=&get_env_multiple('form.grade_domain');
9253: ($name)=&get_env_multiple('form.grade_username');
9254: return ($symb,$courseid,$domain,$name,$publicuser);
9255: }
9256: }
9257: if (!$passedsymb) {
9258: $symb=&symbread();
9259: } else {
9260: $symb=$passedsymb;
9261: }
9262: $courseid=$env{'request.course.id'};
9263: $domain=$env{'user.domain'};
9264: $name=$env{'user.name'};
9265: if ($name eq 'public' && $domain eq 'public') {
9266: if (!defined($env{'form.username'})) {
9267: $env{'form.username'}.=time.rand(10000000);
9268: }
9269: $name.=$env{'form.username'};
9270: }
9271: return ($symb,$courseid,$domain,$name,$publicuser);
9272:
9273: }
9274:
1.36 albertel 9275: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9276: # returns either the contents of the file or
9277: # -1 if the file doesn't exist
1.481 raeburn 9278: #
9279: # if the target is a file that was uploaded via DOCS,
9280: # a check will be made to see if a current copy exists on the local server,
9281: # if it does this will be served, otherwise a copy will be retrieved from
9282: # the home server for the course and stored in /home/httpd/html/userfiles on
9283: # the local server.
1.472 albertel 9284:
1.36 albertel 9285: sub getfile {
1.538 albertel 9286: my ($file) = @_;
1.609 banghart 9287: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9288: &repcopy($file);
9289: return &readfile($file);
9290: }
9291:
9292: sub repcopy_userfile {
9293: my ($file)=@_;
1.609 banghart 9294: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9295: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9296: my ($cdom,$cnum,$filename) =
1.811 albertel 9297: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9298: my $uri="/uploaded/$cdom/$cnum/$filename";
9299: if (-e "$file") {
1.828 www 9300: # we already have a local copy, check it out
1.538 albertel 9301: my @fileinfo = stat($file);
1.828 www 9302: my $rtncode;
9303: my $info;
1.538 albertel 9304: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9305: if ($lwpresp ne 'ok') {
1.828 www 9306: # there is no such file anymore, even though we had a local copy
1.482 albertel 9307: if ($rtncode eq '404') {
1.538 albertel 9308: unlink($file);
1.482 albertel 9309: }
9310: return -1;
9311: }
9312: if ($info < $fileinfo[9]) {
1.828 www 9313: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9314: return 'ok';
1.828 www 9315: } else {
9316: # the file is outdated, get rid of it
9317: unlink($file);
1.482 albertel 9318: }
1.828 www 9319: }
9320: # one way or the other, at this point, we don't have the file
9321: # construct the correct path for the file
9322: my @parts = ($cdom,$cnum);
9323: if ($filename =~ m|^(.+)/[^/]+$|) {
9324: push @parts, split(/\//,$1);
9325: }
9326: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9327: foreach my $part (@parts) {
9328: $path .= '/'.$part;
9329: if (!-e $path) {
9330: mkdir($path,0770);
1.482 albertel 9331: }
9332: }
1.828 www 9333: # now the path exists for sure
9334: # get a user agent
9335: my $ua=new LWP::UserAgent;
9336: my $transferfile=$file.'.in.transfer';
9337: # FIXME: this should flock
9338: if (-e $transferfile) { return 'ok'; }
9339: my $request;
9340: $uri=~s/^\///;
1.980 raeburn 9341: my $homeserver = &homeserver($cnum,$cdom);
9342: my $protocol = $protocol{$homeserver};
9343: $protocol = 'http' if ($protocol ne 'https');
9344: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9345: my $response=$ua->request($request,$transferfile);
9346: # did it work?
9347: if ($response->is_error()) {
9348: unlink($transferfile);
9349: &logthis("Userfile repcopy failed for $uri");
9350: return -1;
9351: }
9352: # worked, rename the transfer file
9353: rename($transferfile,$file);
1.607 raeburn 9354: return 'ok';
1.481 raeburn 9355: }
9356:
1.517 albertel 9357: sub tokenwrapper {
9358: my $uri=shift;
1.980 raeburn 9359: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9360: $uri=~s|^/||;
1.620 albertel 9361: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9362: my $token=$1;
1.552 albertel 9363: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9364: if ($udom && $uname && $file) {
9365: $file=~s|(\?\.*)*$||;
1.949 raeburn 9366: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9367: my $homeserver = &homeserver($uname,$udom);
9368: my $protocol = $protocol{$homeserver};
9369: $protocol = 'http' if ($protocol ne 'https');
9370: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9371: (($uri=~/\?/)?'&':'?').'token='.$token.
9372: '&tokenissued='.$perlvar{'lonHostID'};
9373: } else {
9374: return '/adm/notfound.html';
9375: }
9376: }
9377:
1.828 www 9378: # call with reqtype HEAD: get last modification time
9379: # call with reqtype GET: get the file contents
9380: # Do not call this with reqtype GET for large files! It loads everything into memory
9381: #
1.481 raeburn 9382: sub getuploaded {
9383: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9384: $uri=~s/^\///;
1.980 raeburn 9385: my $homeserver = &homeserver($cnum,$cdom);
9386: my $protocol = $protocol{$homeserver};
9387: $protocol = 'http' if ($protocol ne 'https');
9388: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9389: my $ua=new LWP::UserAgent;
9390: my $request=new HTTP::Request($reqtype,$uri);
9391: my $response=$ua->request($request);
9392: $$rtncode = $response->code;
1.482 albertel 9393: if (! $response->is_success()) {
9394: return 'failed';
9395: }
9396: if ($reqtype eq 'HEAD') {
1.486 www 9397: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9398: } elsif ($reqtype eq 'GET') {
9399: $$info = $response->content;
1.472 albertel 9400: }
1.482 albertel 9401: return 'ok';
1.36 albertel 9402: }
9403:
1.481 raeburn 9404: sub readfile {
9405: my $file = shift;
9406: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9407: my $fh;
9408: open($fh,"<$file");
9409: my $a='';
1.800 albertel 9410: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9411: return $a;
9412: }
9413:
1.36 albertel 9414: sub filelocation {
1.590 banghart 9415: my ($dir,$file) = @_;
9416: my $location;
9417: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9418:
9419: if ($file =~ m-^/adm/-) {
9420: $file=~s-^/adm/wrapper/-/-;
9421: $file=~s-^/adm/coursedocs/showdoc/-/-;
9422: }
1.882 albertel 9423:
1.590 banghart 9424: if ($file=~m:^/~:) { # is a contruction space reference
9425: $location = $file;
9426: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9427: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9428: # is a correct contruction space reference
9429: $location = $file;
1.956 raeburn 9430: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9431: $location = $file;
1.609 banghart 9432: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9433: my ($udom,$uname,$filename)=
1.811 albertel 9434: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9435: my $home=&homeserver($uname,$udom);
9436: my $is_me=0;
9437: my @ids=¤t_machine_ids();
9438: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9439: if ($is_me) {
1.955 raeburn 9440: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9441: } else {
9442: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9443: $udom.'/'.$uname.'/'.$filename;
9444: }
1.882 albertel 9445: } elsif ($file =~ m-^/adm/-) {
9446: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9447: } else {
9448: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9449: $file=~s:^/res/:/:;
9450: if ( !( $file =~ m:^/:) ) {
9451: $location = $dir. '/'.$file;
9452: } else {
9453: $location = '/home/httpd/html/res'.$file;
9454: }
1.59 albertel 9455: }
1.590 banghart 9456: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9457: while ($location=~m{/\.\./}) {
9458: if ($location =~ m{/[^/]+/\.\./}) {
9459: $location=~ s{/[^/]+/\.\./}{/}g;
9460: } else {
9461: $location=~ s{/\.\./}{/}g;
9462: }
9463: } #remove dir/..
1.590 banghart 9464: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9465: return $location;
1.46 www 9466: }
1.36 albertel 9467:
1.46 www 9468: sub hreflocation {
9469: my ($dir,$file)=@_;
1.980 raeburn 9470: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9471: $file=filelocation($dir,$file);
1.700 albertel 9472: } elsif ($file=~m-^/adm/-) {
9473: $file=~s-^/adm/wrapper/-/-;
9474: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9475: }
9476: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9477: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9478: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9479: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9480: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9481: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9482: -/uploaded/$1/$2/-x;
1.46 www 9483: }
1.913 albertel 9484: if ($file=~ m{^/userfiles/}) {
9485: $file =~ s{^/userfiles/}{/uploaded/};
9486: }
1.462 albertel 9487: return $file;
1.465 albertel 9488: }
9489:
9490: sub current_machine_domains {
1.853 albertel 9491: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9492: }
9493:
9494: sub machine_domains {
9495: my ($hostname) = @_;
1.465 albertel 9496: my @domains;
1.838 albertel 9497: my %hostname = &all_hostnames();
1.465 albertel 9498: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9499: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9500: if ($hostname eq $name) {
1.844 albertel 9501: push(@domains,&host_domain($id));
1.465 albertel 9502: }
9503: }
9504: return @domains;
9505: }
9506:
9507: sub current_machine_ids {
1.853 albertel 9508: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9509: }
9510:
9511: sub machine_ids {
9512: my ($hostname) = @_;
9513: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9514: my @ids;
1.888 albertel 9515: my %name_to_host = &all_names();
1.889 albertel 9516: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9517: return @{ $name_to_host{$hostname} };
9518: }
9519: return;
1.31 www 9520: }
9521:
1.824 raeburn 9522: sub additional_machine_domains {
9523: my @domains;
9524: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9525: while( my $line = <$fh>) {
9526: $line =~ s/\s//g;
9527: push(@domains,$line);
9528: }
9529: return @domains;
9530: }
9531:
9532: sub default_login_domain {
9533: my $domain = $perlvar{'lonDefDomain'};
9534: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9535: foreach my $posdom (¤t_machine_domains(),
9536: &additional_machine_domains()) {
9537: if (lc($posdom) eq lc($testdomain)) {
9538: $domain=$posdom;
9539: last;
9540: }
9541: }
9542: return $domain;
9543: }
9544:
1.31 www 9545: # ------------------------------------------------------------- Declutters URLs
9546:
9547: sub declutter {
9548: my $thisfn=shift;
1.569 albertel 9549: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9550: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9551: $thisfn=~s/^\///;
1.697 albertel 9552: $thisfn=~s|^adm/wrapper/||;
9553: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9554: $thisfn=~s/^res\///;
1.1032 raeburn 9555: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9556: $thisfn=~s/\?.+$//;
9557: }
1.268 www 9558: return $thisfn;
9559: }
9560:
9561: # ------------------------------------------------------------- Clutter up URLs
9562:
9563: sub clutter {
9564: my $thisfn='/'.&declutter(shift);
1.887 albertel 9565: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9566: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9567: $thisfn='/res'.$thisfn;
9568: }
1.1031 raeburn 9569: if ($thisfn !~m|^/adm|) {
9570: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9571: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9572: } else {
9573: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9574: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9575: if ($embstyle eq 'ssi'
9576: || ($embstyle eq 'hdn')
9577: || ($embstyle eq 'rat')
9578: || ($embstyle eq 'prv')
9579: || ($embstyle eq 'ign')) {
9580: #do nothing with these
9581: } elsif (($embstyle eq 'img')
1.695 albertel 9582: || ($embstyle eq 'emb')
9583: || ($embstyle eq 'wrp')) {
9584: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9585: } elsif ($embstyle eq 'unk'
9586: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9587: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9588: } else {
1.718 www 9589: # &logthis("Got a blank emb style");
1.695 albertel 9590: }
1.694 albertel 9591: }
9592: }
1.31 www 9593: return $thisfn;
1.12 www 9594: }
9595:
1.787 albertel 9596: sub clutter_with_no_wrapper {
9597: my $uri = &clutter(shift);
9598: if ($uri =~ m-^/adm/-) {
9599: $uri =~ s-^/adm/wrapper/-/-;
9600: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9601: }
9602: return $uri;
9603: }
9604:
1.557 albertel 9605: sub freeze_escape {
9606: my ($value)=@_;
9607: if (ref($value)) {
9608: $value=&nfreeze($value);
9609: return '__FROZEN__'.&escape($value);
9610: }
9611: return &escape($value);
9612: }
9613:
1.11 www 9614:
1.557 albertel 9615: sub thaw_unescape {
9616: my ($value)=@_;
9617: if ($value =~ /^__FROZEN__/) {
9618: substr($value,0,10,undef);
9619: $value=&unescape($value);
9620: return &thaw($value);
9621: }
9622: return &unescape($value);
9623: }
9624:
1.436 albertel 9625: sub correct_line_ends {
9626: my ($result)=@_;
9627: $$result =~s/\r\n/\n/mg;
9628: $$result =~s/\r/\n/mg;
1.415 albertel 9629: }
1.1 albertel 9630: # ================================================================ Main Program
9631:
1.184 www 9632: sub goodbye {
1.204 albertel 9633: &logthis("Starting Shut down");
1.443 albertel 9634: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9635: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9636: #converted
1.599 albertel 9637: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9638: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9639: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9640: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9641: #1.1 only
1.870 albertel 9642: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9643: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9644: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9645: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9646: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9647: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9648: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9649: &flushcourselogs();
9650: &logthis("Shutting down");
9651: }
9652:
1.852 albertel 9653: sub get_dns {
1.869 albertel 9654: my ($url,$func,$ignore_cache) = @_;
9655: if (!$ignore_cache) {
9656: my ($content,$cached)=
9657: &Apache::lonnet::is_cached_new('dns',$url);
9658: if ($cached) {
9659: &$func($content);
9660: return;
9661: }
9662: }
9663:
9664: my %alldns;
1.852 albertel 9665: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9666: foreach my $dns (<$config>) {
9667: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9668: my $line = $1;
9669: my ($host,$protocol) = split(/:/,$line);
9670: if ($protocol ne 'https') {
9671: $protocol = 'http';
9672: }
9673: $alldns{$host} = $protocol;
1.869 albertel 9674: }
9675: while (%alldns) {
9676: my ($dns) = keys(%alldns);
1.852 albertel 9677: my $ua=new LWP::UserAgent;
1.979 raeburn 9678: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9679: my $response=$ua->request($request);
1.979 raeburn 9680: delete($alldns{$dns});
1.852 albertel 9681: next if ($response->is_error());
9682: my @content = split("\n",$response->content);
1.869 albertel 9683: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9684: &$func(\@content);
1.869 albertel 9685: return;
1.852 albertel 9686: }
9687: close($config);
1.871 albertel 9688: my $which = (split('/',$url))[3];
9689: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9690: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9691: my @content = <$config>;
9692: &$func(\@content);
9693: return;
1.852 albertel 9694: }
1.327 albertel 9695: # ------------------------------------------------------------ Read domain file
9696: {
1.852 albertel 9697: my $loaded;
1.846 albertel 9698: my %domain;
9699:
1.852 albertel 9700: sub parse_domain_tab {
9701: my ($lines) = @_;
9702: foreach my $line (@$lines) {
9703: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9704:
1.846 albertel 9705: chomp($line);
1.852 albertel 9706: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9707: my %this_domain;
9708: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9709: 'lang_def', 'city', 'longi', 'lati',
9710: 'primary') {
9711: $this_domain{$field} = shift(@elements);
9712: }
9713: $domain{$name} = \%this_domain;
1.852 albertel 9714: }
9715: }
1.864 albertel 9716:
9717: sub reset_domain_info {
9718: undef($loaded);
9719: undef(%domain);
9720: }
9721:
1.852 albertel 9722: sub load_domain_tab {
1.869 albertel 9723: my ($ignore_cache) = @_;
9724: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9725: my $fh;
9726: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9727: my @lines = <$fh>;
9728: &parse_domain_tab(\@lines);
1.448 albertel 9729: }
1.852 albertel 9730: close($fh);
9731: $loaded = 1;
1.327 albertel 9732: }
1.846 albertel 9733:
9734: sub domain {
1.852 albertel 9735: &load_domain_tab() if (!$loaded);
9736:
1.846 albertel 9737: my ($name,$what) = @_;
9738: return if ( !exists($domain{$name}) );
9739:
9740: if (!$what) {
9741: return $domain{$name}{'description'};
9742: }
9743: return $domain{$name}{$what};
9744: }
1.974 raeburn 9745:
9746: sub domain_info {
9747: &load_domain_tab() if (!$loaded);
9748: return %domain;
9749: }
9750:
1.327 albertel 9751: }
9752:
9753:
1.1 albertel 9754: # ------------------------------------------------------------- Read hosts file
9755: {
1.838 albertel 9756: my %hostname;
1.844 albertel 9757: my %hostdom;
1.845 albertel 9758: my %libserv;
1.852 albertel 9759: my $loaded;
1.888 albertel 9760: my %name_to_host;
1.852 albertel 9761:
9762: sub parse_hosts_tab {
9763: my ($file) = @_;
9764: foreach my $configline (@$file) {
9765: next if ($configline =~ /^(\#|\s*$ )/x);
9766: next if ($configline =~ /^\^/);
9767: chomp($configline);
1.968 raeburn 9768: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9769: $name=~s/\s//g;
9770: if ($id && $domain && $role && $name) {
9771: $hostname{$id}=$name;
1.888 albertel 9772: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9773: $hostdom{$id}=$domain;
9774: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9775: if (defined($protocol)) {
9776: if ($protocol eq 'https') {
9777: $protocol{$id} = $protocol;
9778: } else {
9779: $protocol{$id} = 'http';
9780: }
1.968 raeburn 9781: } else {
1.969 raeburn 9782: $protocol{$id} = 'http';
1.968 raeburn 9783: }
1.852 albertel 9784: }
9785: }
9786: }
1.864 albertel 9787:
9788: sub reset_hosts_info {
1.897 albertel 9789: &purge_remembered();
1.864 albertel 9790: &reset_domain_info();
9791: &reset_hosts_ip_info();
1.892 albertel 9792: undef(%name_to_host);
1.864 albertel 9793: undef(%hostname);
9794: undef(%hostdom);
9795: undef(%libserv);
9796: undef($loaded);
9797: }
1.1 albertel 9798:
1.852 albertel 9799: sub load_hosts_tab {
1.869 albertel 9800: my ($ignore_cache) = @_;
9801: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9802: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9803: my @config = <$config>;
9804: &parse_hosts_tab(\@config);
9805: close($config);
9806: $loaded=1;
1.1 albertel 9807: }
1.852 albertel 9808:
1.838 albertel 9809: sub hostname {
1.852 albertel 9810: &load_hosts_tab() if (!$loaded);
9811:
1.838 albertel 9812: my ($lonid) = @_;
9813: return $hostname{$lonid};
9814: }
1.845 albertel 9815:
1.838 albertel 9816: sub all_hostnames {
1.852 albertel 9817: &load_hosts_tab() if (!$loaded);
9818:
1.838 albertel 9819: return %hostname;
9820: }
1.845 albertel 9821:
1.888 albertel 9822: sub all_names {
9823: &load_hosts_tab() if (!$loaded);
9824:
9825: return %name_to_host;
9826: }
9827:
1.974 raeburn 9828: sub all_host_domain {
9829: &load_hosts_tab() if (!$loaded);
9830: return %hostdom;
9831: }
9832:
1.845 albertel 9833: sub is_library {
1.852 albertel 9834: &load_hosts_tab() if (!$loaded);
9835:
1.845 albertel 9836: return exists($libserv{$_[0]});
9837: }
9838:
9839: sub all_library {
1.852 albertel 9840: &load_hosts_tab() if (!$loaded);
9841:
1.845 albertel 9842: return %libserv;
9843: }
9844:
1.841 albertel 9845: sub get_servers {
1.852 albertel 9846: &load_hosts_tab() if (!$loaded);
9847:
1.841 albertel 9848: my ($domain,$type) = @_;
9849: my %possible_hosts = ($type eq 'library') ? %libserv
9850: : %hostname;
9851: my %result;
1.842 albertel 9852: if (ref($domain) eq 'ARRAY') {
9853: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9854: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9855: $result{$host} = $hostname;
9856: }
9857: }
9858: } else {
9859: while ( my ($host,$hostname) = each(%possible_hosts)) {
9860: if ($hostdom{$host} eq $domain) {
9861: $result{$host} = $hostname;
9862: }
1.841 albertel 9863: }
9864: }
9865: return %result;
9866: }
1.845 albertel 9867:
1.844 albertel 9868: sub host_domain {
1.852 albertel 9869: &load_hosts_tab() if (!$loaded);
9870:
1.844 albertel 9871: my ($lonid) = @_;
9872: return $hostdom{$lonid};
9873: }
9874:
1.841 albertel 9875: sub all_domains {
1.852 albertel 9876: &load_hosts_tab() if (!$loaded);
9877:
1.841 albertel 9878: my %seen;
9879: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9880: return @uniq;
9881: }
1.1 albertel 9882: }
9883:
1.847 albertel 9884: {
9885: my %iphost;
1.856 albertel 9886: my %name_to_ip;
9887: my %lonid_to_ip;
1.869 albertel 9888:
1.847 albertel 9889: sub get_hosts_from_ip {
9890: my ($ip) = @_;
9891: my %iphosts = &get_iphost();
9892: if (ref($iphosts{$ip})) {
9893: return @{$iphosts{$ip}};
9894: }
9895: return;
1.839 albertel 9896: }
1.864 albertel 9897:
9898: sub reset_hosts_ip_info {
9899: undef(%iphost);
9900: undef(%name_to_ip);
9901: undef(%lonid_to_ip);
9902: }
1.856 albertel 9903:
9904: sub get_host_ip {
9905: my ($lonid) = @_;
9906: if (exists($lonid_to_ip{$lonid})) {
9907: return $lonid_to_ip{$lonid};
9908: }
9909: my $name=&hostname($lonid);
9910: my $ip = gethostbyname($name);
9911: return if (!$ip || length($ip) ne 4);
9912: $ip=inet_ntoa($ip);
9913: $name_to_ip{$name} = $ip;
9914: $lonid_to_ip{$lonid} = $ip;
9915: return $ip;
9916: }
1.847 albertel 9917:
9918: sub get_iphost {
1.869 albertel 9919: my ($ignore_cache) = @_;
1.894 albertel 9920:
1.869 albertel 9921: if (!$ignore_cache) {
9922: if (%iphost) {
9923: return %iphost;
9924: }
9925: my ($ip_info,$cached)=
9926: &Apache::lonnet::is_cached_new('iphost','iphost');
9927: if ($cached) {
9928: %iphost = %{$ip_info->[0]};
9929: %name_to_ip = %{$ip_info->[1]};
9930: %lonid_to_ip = %{$ip_info->[2]};
9931: return %iphost;
9932: }
9933: }
1.894 albertel 9934:
9935: # get yesterday's info for fallback
9936: my %old_name_to_ip;
9937: my ($ip_info,$cached)=
9938: &Apache::lonnet::is_cached_new('iphost','iphost');
9939: if ($cached) {
9940: %old_name_to_ip = %{$ip_info->[1]};
9941: }
9942:
1.888 albertel 9943: my %name_to_host = &all_names();
9944: foreach my $name (keys(%name_to_host)) {
1.847 albertel 9945: my $ip;
9946: if (!exists($name_to_ip{$name})) {
9947: $ip = gethostbyname($name);
9948: if (!$ip || length($ip) ne 4) {
1.894 albertel 9949: if (defined($old_name_to_ip{$name})) {
9950: $ip = $old_name_to_ip{$name};
9951: &logthis("Can't find $name defaulting to old $ip");
9952: } else {
9953: &logthis("Name $name no IP found");
9954: next;
9955: }
9956: } else {
9957: $ip=inet_ntoa($ip);
1.847 albertel 9958: }
9959: $name_to_ip{$name} = $ip;
9960: } else {
9961: $ip = $name_to_ip{$name};
1.653 albertel 9962: }
1.888 albertel 9963: foreach my $id (@{ $name_to_host{$name} }) {
9964: $lonid_to_ip{$id} = $ip;
9965: }
9966: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 9967: }
1.869 albertel 9968: &Apache::lonnet::do_cache_new('iphost','iphost',
9969: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 9970: 48*60*60);
1.869 albertel 9971:
1.847 albertel 9972: return %iphost;
1.598 albertel 9973: }
9974:
1.992 raeburn 9975: #
9976: # Given a DNS returns the loncapa host name for that DNS
9977: #
9978: sub host_from_dns {
9979: my ($dns) = @_;
9980: my @hosts;
9981: my $ip;
9982:
1.993 raeburn 9983: if (exists($name_to_ip{$dns})) {
1.992 raeburn 9984: $ip = $name_to_ip{$dns};
9985: }
9986: if (!$ip) {
9987: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9988: if (length($ip) == 4) {
9989: $ip = &IO::Socket::inet_ntoa($ip);
9990: }
9991: }
9992: if ($ip) {
9993: @hosts = get_hosts_from_ip($ip);
9994: return $hosts[0];
9995: }
9996: return undef;
1.986 foxr 9997: }
1.992 raeburn 9998:
1.986 foxr 9999: }
10000:
1.862 albertel 10001: BEGIN {
10002:
10003: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10004: unless ($readit) {
10005: {
10006: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10007: %perlvar = (%perlvar,%{$configvars});
10008: }
10009:
10010:
1.1 albertel 10011: # ------------------------------------------------------ Read spare server file
10012: {
1.448 albertel 10013: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10014:
10015: while (my $configline=<$config>) {
10016: chomp($configline);
1.284 matthew 10017: if ($configline) {
1.784 albertel 10018: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10019: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10020: push(@{ $spareid{$type} }, $host);
1.1 albertel 10021: }
10022: }
1.448 albertel 10023: close($config);
1.1 albertel 10024: }
1.11 www 10025: # ------------------------------------------------------------ Read permissions
10026: {
1.448 albertel 10027: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10028:
10029: while (my $configline=<$config>) {
1.448 albertel 10030: chomp($configline);
10031: if ($configline) {
10032: my ($role,$perm)=split(/ /,$configline);
10033: if ($perm ne '') { $pr{$role}=$perm; }
10034: }
1.11 www 10035: }
1.448 albertel 10036: close($config);
1.11 www 10037: }
10038:
10039: # -------------------------------------------- Read plain texts for permissions
10040: {
1.448 albertel 10041: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10042:
10043: while (my $configline=<$config>) {
1.448 albertel 10044: chomp($configline);
10045: if ($configline) {
1.742 raeburn 10046: my ($short,@plain)=split(/:/,$configline);
10047: %{$prp{$short}} = ();
10048: if (@plain > 0) {
10049: $prp{$short}{'std'} = $plain[0];
10050: for (my $i=1; $i<@plain; $i++) {
10051: $prp{$short}{'alt'.$i} = $plain[$i];
10052: }
10053: }
1.448 albertel 10054: }
1.135 www 10055: }
1.448 albertel 10056: close($config);
1.135 www 10057: }
10058:
10059: # ---------------------------------------------------------- Read package table
10060: {
1.448 albertel 10061: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10062:
10063: while (my $configline=<$config>) {
1.483 albertel 10064: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10065: chomp($configline);
10066: my ($short,$plain)=split(/:/,$configline);
10067: my ($pack,$name)=split(/\&/,$short);
10068: if ($plain ne '') {
10069: $packagetab{$pack.'&'.$name.'&name'}=$name;
10070: $packagetab{$short}=$plain;
10071: }
1.11 www 10072: }
1.448 albertel 10073: close($config);
1.329 matthew 10074: }
10075:
10076: # ------------- set up temporary directory
10077: {
10078: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10079:
1.11 www 10080: }
10081:
1.794 albertel 10082: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10083: 'compress_threshold'=> 20_000,
10084: });
1.185 www 10085:
1.281 www 10086: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10087: $dumpcount=0;
1.958 www 10088: $locknum=0;
1.22 www 10089:
1.163 harris41 10090: &logtouch();
1.672 albertel 10091: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10092: $readit=1;
1.564 albertel 10093: {
10094: use integer;
10095: my $test=(2**32)+1;
1.568 albertel 10096: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10097: &logthis(" Detected 64bit platform ($_64bit)");
10098: }
1.195 www 10099: }
1.1 albertel 10100: }
1.179 www 10101:
1.1 albertel 10102: 1;
1.191 harris41 10103: __END__
10104:
1.243 albertel 10105: =pod
10106:
1.191 harris41 10107: =head1 NAME
10108:
1.243 albertel 10109: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10110:
10111: =head1 SYNOPSIS
10112:
1.243 albertel 10113: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10114:
10115: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10116:
1.243 albertel 10117: Common parameters:
10118:
10119: =over 4
10120:
10121: =item *
10122:
10123: $uname : an internal username (if $cname expecting a course Id specifically)
10124:
10125: =item *
10126:
10127: $udom : a domain (if $cdom expecting a course's domain specifically)
10128:
10129: =item *
10130:
10131: $symb : a resource instance identifier
10132:
10133: =item *
10134:
10135: $namespace : the name of a .db file that contains the data needed or
10136: being set.
10137:
10138: =back
10139:
1.394 bowersj2 10140: =head1 OVERVIEW
1.191 harris41 10141:
1.394 bowersj2 10142: lonnet provides subroutines which interact with the
10143: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10144: about classes, users, and resources.
1.243 albertel 10145:
10146: For many of these objects you can also use this to store data about
10147: them or modify them in various ways.
1.191 harris41 10148:
1.394 bowersj2 10149: =head2 Symbs
1.191 harris41 10150:
1.394 bowersj2 10151: To identify a specific instance of a resource, LON-CAPA uses symbols
10152: or "symbs"X<symb>. These identifiers are built from the URL of the
10153: map, the resource number of the resource in the map, and the URL of
10154: the resource itself. The latter is somewhat redundant, but might help
10155: if maps change.
10156:
10157: An example is
10158:
10159: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10160:
10161: The respective map entry is
10162:
10163: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10164: title="Problem 2">
10165: </resource>
10166:
10167: Symbs are used by the random number generator, as well as to store and
10168: restore data specific to a certain instance of for example a problem.
10169:
10170: =head2 Storing And Retrieving Data
10171:
10172: X<store()>X<cstore()>X<restore()>Three of the most important functions
10173: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10174: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10175: is is the non-critical message twin of cstore. These functions are for
10176: handlers to store a perl hash to a user's permanent data space in an
10177: easy manner, and to retrieve it again on another call. It is expected
10178: that a handler would use this once at the beginning to retrieve data,
10179: and then again once at the end to send only the new data back.
10180:
10181: The data is stored in the user's data directory on the user's
10182: homeserver under the ID of the course.
10183:
10184: The hash that is returned by restore will have all of the previous
10185: value for all of the elements of the hash.
10186:
10187: Example:
10188:
10189: #creating a hash
10190: my %hash;
10191: $hash{'foo'}='bar';
10192:
10193: #storing it
10194: &Apache::lonnet::cstore(\%hash);
10195:
10196: #changing a value
10197: $hash{'foo'}='notbar';
10198:
10199: #adding a new value
10200: $hash{'bar'}='foo';
10201: &Apache::lonnet::cstore(\%hash);
10202:
10203: #retrieving the hash
10204: my %history=&Apache::lonnet::restore();
10205:
10206: #print the hash
10207: foreach my $key (sort(keys(%history))) {
10208: print("\%history{$key} = $history{$key}");
10209: }
10210:
10211: Will print out:
1.191 harris41 10212:
1.394 bowersj2 10213: %history{1:foo} = bar
10214: %history{1:keys} = foo:timestamp
10215: %history{1:timestamp} = 990455579
10216: %history{2:bar} = foo
10217: %history{2:foo} = notbar
10218: %history{2:keys} = foo:bar:timestamp
10219: %history{2:timestamp} = 990455580
10220: %history{bar} = foo
10221: %history{foo} = notbar
10222: %history{timestamp} = 990455580
10223: %history{version} = 2
10224:
10225: Note that the special hash entries C<keys>, C<version> and
10226: C<timestamp> were added to the hash. C<version> will be equal to the
10227: total number of versions of the data that have been stored. The
10228: C<timestamp> attribute will be the UNIX time the hash was
10229: stored. C<keys> is available in every historical section to list which
10230: keys were added or changed at a specific historical revision of a
10231: hash.
10232:
10233: B<Warning>: do not store the hash that restore returns directly. This
10234: will cause a mess since it will restore the historical keys as if the
10235: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10236:
1.394 bowersj2 10237: Calling convention:
1.191 harris41 10238:
1.394 bowersj2 10239: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10240: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10241:
1.394 bowersj2 10242: For more detailed information, see lonnet specific documentation.
1.191 harris41 10243:
1.394 bowersj2 10244: =head1 RETURN MESSAGES
1.191 harris41 10245:
1.394 bowersj2 10246: =over 4
1.191 harris41 10247:
1.394 bowersj2 10248: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10249:
1.394 bowersj2 10250: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10251: when the connection is brought back up
1.191 harris41 10252:
1.394 bowersj2 10253: =item * B<con_failed>: unable to contact remote host and unable to save message
10254: for later delivery
1.191 harris41 10255:
1.967 bisitz 10256: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10257:
1.394 bowersj2 10258: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10259: that was requested
1.191 harris41 10260:
1.243 albertel 10261: =back
1.191 harris41 10262:
1.243 albertel 10263: =head1 PUBLIC SUBROUTINES
1.191 harris41 10264:
1.243 albertel 10265: =head2 Session Environment Functions
1.191 harris41 10266:
1.243 albertel 10267: =over 4
1.191 harris41 10268:
1.394 bowersj2 10269: =item *
10270: X<appenv()>
1.949 raeburn 10271: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10272: the user envirnoment file, and will be restored for each access this
1.620 albertel 10273: user makes during this session, also modifies the %env for the current
1.949 raeburn 10274: process. Optional rolesarrayref - if defined contains a reference to an array
10275: of roles which are exempt from the restriction on modifying user.role entries
10276: in the user's environment.db and in %env.
1.191 harris41 10277:
10278: =item *
1.394 bowersj2 10279: X<delenv()>
1.987 raeburn 10280: B<delenv($delthis,$regexp)>: removes all items from the session
10281: environment file that begin with $delthis. If the
10282: optional second arg - $regexp - is true, $delthis is treated as a
10283: regular expression, otherwise \Q$delthis\E is used.
10284: The values are also deleted from the current processes %env.
1.191 harris41 10285:
1.795 albertel 10286: =item * get_env_multiple($name)
10287:
10288: gets $name from the %env hash, it seemlessly handles the cases where multiple
10289: values may be defined and end up as an array ref.
10290:
10291: returns an array of values
10292:
1.243 albertel 10293: =back
10294:
10295: =head2 User Information
1.191 harris41 10296:
1.243 albertel 10297: =over 4
1.191 harris41 10298:
10299: =item *
1.394 bowersj2 10300: X<queryauthenticate()>
10301: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10302: authentication scheme
10303:
10304: =item *
1.394 bowersj2 10305: X<authenticate()>
10306: B<authenticate($uname,$upass,$udom)>: try to
10307: authenticate user from domain's lib servers (first use the current
10308: one). C<$upass> should be the users password.
1.191 harris41 10309:
10310: =item *
1.394 bowersj2 10311: X<homeserver()>
10312: B<homeserver($uname,$udom)>: find the server which has
10313: the user's directory and files (there must be only one), this caches
10314: the answer, and also caches if there is a borken connection.
1.191 harris41 10315:
10316: =item *
1.394 bowersj2 10317: X<idget()>
10318: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10319: (IDs are a unique resource in a domain, there must be only 1 ID per
10320: username, and only 1 username per ID in a specific domain) (returns
10321: hash: id=>name,id=>name)
1.191 harris41 10322:
10323: =item *
1.394 bowersj2 10324: X<idrget()>
10325: B<idrget($udom,@unames)>: find the IDs behind a list of
10326: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10327:
10328: =item *
1.394 bowersj2 10329: X<idput()>
10330: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10331:
10332: =item *
1.394 bowersj2 10333: X<rolesinit()>
10334: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10335:
10336: =item *
1.551 albertel 10337: X<getsection()>
10338: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10339: course $cname, return section name/number or '' for "not in course"
10340: and '-1' for "no section"
10341:
10342: =item *
1.394 bowersj2 10343: X<userenvironment()>
10344: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10345: passed in @what from the requested user's environment, returns a hash
10346:
1.858 raeburn 10347: =item *
10348: X<userlog_query()>
1.859 albertel 10349: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10350: activity.log file. %filters defines filters applied when parsing the
10351: log file. These can be start or end timestamps, or the type of action
10352: - log to look for Login or Logout events, check for Checkin or
10353: Checkout, role for role selection. The response is in the form
10354: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10355: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10356:
1.243 albertel 10357: =back
10358:
10359: =head2 User Roles
10360:
10361: =over 4
10362:
10363: =item *
10364:
1.810 raeburn 10365: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10366: F: full access
10367: U,I,K: authentication modes (cxx only)
10368: '': forbidden
10369: 1: user needs to choose course
10370: 2: browse allowed
1.766 albertel 10371: A: passphrase authentication needed
1.243 albertel 10372:
10373: =item *
10374:
10375: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10376: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10377: and course level
10378:
10379: =item *
10380:
1.988 raeburn 10381: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10382: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10383: $type is Course (default) or Community.
1.988 raeburn 10384: If $forcedefault evaluates to true, text returned will be default
10385: text for $type. Otherwise, if this is a course, the text returned
10386: will be a custom name for the role (if defined in the course's
10387: environment). If no custom name is defined the default is returned.
10388:
1.832 raeburn 10389: =item *
10390:
1.935 raeburn 10391: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10392: All arguments are optional. Returns a hash of a roles, either for
10393: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10394: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10395: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10396: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10397: For each key, value is set to colon-separated start and end times for
10398: the role. If no username and domain are specified, will default to
1.934 raeburn 10399: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10400: of role statuses (active, future or previous), roles
10401: (e.g., cc,in, st etc.) and domains of the roles which can be used
10402: to restrict the list of roles reported. If no array ref is
10403: provided for types, will default to return only active roles.
1.834 albertel 10404:
1.243 albertel 10405: =back
10406:
10407: =head2 User Modification
10408:
10409: =over 4
10410:
10411: =item *
10412:
1.957 raeburn 10413: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10414: user for the level given by URL. Optional start and end dates (leave empty
10415: string or zero for "no date")
1.191 harris41 10416:
10417: =item *
10418:
1.243 albertel 10419: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10420: change a users, password, possible return values are: ok,
10421: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10422: refused
1.191 harris41 10423:
10424: =item *
10425:
1.243 albertel 10426: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10427:
10428: =item *
10429:
1.1056.2.1 raeburn 10430: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10431: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10432:
10433: will update user information (firstname,middlename,lastname,generation,
10434: permanentemail), and if forceid is true, student/employee ID also.
10435: A user's institutional affiliation(s) can also be updated.
10436: User information fields will not be overwritten with empty entries
10437: unless the field is included in the $candelete array reference.
10438: This array is included when a single user is modified via "Manage Users",
10439: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10440:
10441: =item *
10442:
1.286 matthew 10443: modifystudent
10444:
1.957 raeburn 10445: modify a student's enrollment and identification information.
1.286 matthew 10446: The course id is resolved based on the current users environment.
10447: This means the envoking user must be a course coordinator or otherwise
10448: associated with a course.
10449:
1.297 matthew 10450: This call is essentially a wrapper for lonnet::modifyuser and
10451: lonnet::modify_student_enrollment
1.286 matthew 10452:
10453: Inputs:
10454:
10455: =over 4
10456:
1.957 raeburn 10457: =item B<$udom> Student's loncapa domain
1.286 matthew 10458:
1.957 raeburn 10459: =item B<$uname> Student's loncapa login name
1.286 matthew 10460:
1.964 bisitz 10461: =item B<$uid> Student/Employee ID
1.286 matthew 10462:
1.957 raeburn 10463: =item B<$umode> Student's authentication mode
1.286 matthew 10464:
1.957 raeburn 10465: =item B<$upass> Student's password
1.286 matthew 10466:
1.957 raeburn 10467: =item B<$first> Student's first name
1.286 matthew 10468:
1.957 raeburn 10469: =item B<$middle> Student's middle name
1.286 matthew 10470:
1.957 raeburn 10471: =item B<$last> Student's last name
1.286 matthew 10472:
1.957 raeburn 10473: =item B<$gene> Student's generation
1.286 matthew 10474:
1.957 raeburn 10475: =item B<$usec> Student's section in course
1.286 matthew 10476:
10477: =item B<$end> Unix time of the roles expiration
10478:
10479: =item B<$start> Unix time of the roles start date
10480:
10481: =item B<$forceid> If defined, allow $uid to be changed
10482:
10483: =item B<$desiredhome> server to use as home server for student
10484:
1.957 raeburn 10485: =item B<$email> Student's permanent e-mail address
10486:
10487: =item B<$type> Type of enrollment (auto or manual)
10488:
1.963 raeburn 10489: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10490:
10491: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10492:
1.963 raeburn 10493: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10494:
1.963 raeburn 10495: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10496:
1.963 raeburn 10497: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10498:
1.286 matthew 10499: =back
1.297 matthew 10500:
10501: =item *
10502:
10503: modify_student_enrollment
10504:
10505: Change a students enrollment status in a class. The environment variable
10506: 'role.request.course' must be defined for this function to proceed.
10507:
10508: Inputs:
10509:
10510: =over 4
10511:
10512: =item $udom, students domain
10513:
10514: =item $uname, students name
10515:
10516: =item $uid, students user id
10517:
10518: =item $first, students first name
10519:
10520: =item $middle
10521:
10522: =item $last
10523:
10524: =item $gene
10525:
10526: =item $usec
10527:
10528: =item $end
10529:
10530: =item $start
10531:
1.957 raeburn 10532: =item $type
10533:
10534: =item $locktype
10535:
10536: =item $cid
10537:
10538: =item $selfenroll
10539:
10540: =item $context
10541:
1.297 matthew 10542: =back
10543:
1.191 harris41 10544:
10545: =item *
10546:
1.243 albertel 10547: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10548: custom role; give a custom role to a user for the level given by URL. Specify
10549: name and domain of role author, and role name
1.191 harris41 10550:
10551: =item *
10552:
1.243 albertel 10553: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10554:
10555: =item *
10556:
1.243 albertel 10557: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10558:
10559: =back
10560:
10561: =head2 Course Infomation
10562:
10563: =over 4
1.191 harris41 10564:
10565: =item *
10566:
1.631 albertel 10567: coursedescription($courseid) : returns a hash of information about the
10568: specified course id, including all environment settings for the
10569: course, the description of the course will be in the hash under the
10570: key 'description'
1.191 harris41 10571:
10572: =item *
10573:
1.624 albertel 10574: resdata($name,$domain,$type,@which) : request for current parameter
10575: setting for a specific $type, where $type is either 'course' or 'user',
10576: @what should be a list of parameters to ask about. This routine caches
10577: answers for 5 minutes.
1.243 albertel 10578:
1.877 foxr 10579: =item *
10580:
10581: get_courseresdata($courseid, $domain) : dump the entire course resource
10582: data base, returning a hash that is keyed by the resource name and has
10583: values that are the resource value. I believe that the timestamps and
10584: versions are also returned.
10585:
10586:
1.243 albertel 10587: =back
10588:
10589: =head2 Course Modification
10590:
10591: =over 4
1.191 harris41 10592:
10593: =item *
10594:
1.243 albertel 10595: writecoursepref($courseid,%prefs) : write preferences (environment
10596: database) for a course
1.191 harris41 10597:
10598: =item *
10599:
1.1011 raeburn 10600: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10601:
10602: =item *
10603:
1.1038 raeburn 10604: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10605:
10606: =back
10607:
10608: =head2 Resource Subroutines
10609:
10610: =over 4
1.191 harris41 10611:
10612: =item *
10613:
1.243 albertel 10614: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10615:
10616: =item *
10617:
1.243 albertel 10618: repcopy($filename) : subscribes to the requested file, and attempts to
10619: replicate from the owning library server, Might return
1.607 raeburn 10620: 'unavailable', 'not_found', 'forbidden', 'ok', or
10621: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10622: resource. Expects the local filesystem pathname
10623: (/home/httpd/html/res/....)
10624:
10625: =back
10626:
10627: =head2 Resource Information
10628:
10629: =over 4
1.191 harris41 10630:
10631: =item *
10632:
1.243 albertel 10633: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10634: a vairety of different possible values, $varname should be a request
10635: string, and the other parameters can be used to specify who and what
10636: one is asking about.
10637:
10638: Possible values for $varname are environment.lastname (or other item
10639: from the envirnment hash), user.name (or someother aspect about the
10640: user), resource.0.maxtries (or some other part and parameter of a
10641: resource)
1.204 albertel 10642:
10643: =item *
10644:
1.243 albertel 10645: directcondval($number) : get current value of a condition; reads from a state
10646: string
1.204 albertel 10647:
10648: =item *
10649:
1.243 albertel 10650: condval($condidx) : value of condition index based on state
1.204 albertel 10651:
10652: =item *
10653:
1.243 albertel 10654: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10655: resource's metadata, $what should be either a specific key, or either
10656: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10657: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10658:
10659: this function automatically caches all requests
1.191 harris41 10660:
10661: =item *
10662:
1.243 albertel 10663: metadata_query($query,$custom,$customshow) : make a metadata query against the
10664: network of library servers; returns file handle of where SQL and regex results
10665: will be stored for query
1.191 harris41 10666:
10667: =item *
10668:
1.243 albertel 10669: symbread($filename) : return symbolic list entry (filename argument optional);
10670: returns the data handle
1.191 harris41 10671:
10672: =item *
10673:
1.243 albertel 10674: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10675: a possible symb for the URL in $thisfn, and if is an encryypted
10676: resource that the user accessed using /enc/ returns a 1 on success, 0
10677: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10678: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10679:
1.191 harris41 10680:
10681: =item *
10682:
1.243 albertel 10683: symbclean($symb) : removes versions numbers from a symb, returns the
10684: cleaned symb
1.191 harris41 10685:
10686: =item *
10687:
1.243 albertel 10688: is_on_map($uri) : checks if the $uri is somewhere on the current
10689: course map, user must be in a course for it to work.
1.191 harris41 10690:
10691: =item *
10692:
1.243 albertel 10693: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10694:
10695: =item *
10696:
1.243 albertel 10697: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10698: a random seed, all arguments are optional, if they aren't sent it uses the
10699: environment to derive them. Note: if symb isn't sent and it can't get one
10700: from &symbread it will use the current time as its return value
1.191 harris41 10701:
10702: =item *
10703:
1.243 albertel 10704: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10705: unfakeable, receipt
1.191 harris41 10706:
10707: =item *
10708:
1.620 albertel 10709: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10710:
10711: =item *
10712:
1.243 albertel 10713: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10714:
10715: =item *
10716:
1.243 albertel 10717: 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 10718:
10719: =item *
10720:
1.243 albertel 10721: 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 10722:
10723: =item *
10724:
1.243 albertel 10725: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10726:
10727: =item *
10728:
1.243 albertel 10729: devalidate($symb) : devalidate temporary spreadsheet calculations,
10730: forcing spreadsheet to reevaluate the resource scores next time.
10731:
10732: =back
10733:
10734: =head2 Storing/Retreiving Data
10735:
10736: =over 4
1.191 harris41 10737:
10738: =item *
10739:
1.243 albertel 10740: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10741: for this url; hashref needs to be given and should be a \%hashname; the
10742: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10743: be derived from the env
1.191 harris41 10744:
10745: =item *
10746:
1.243 albertel 10747: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10748: uses critical subroutine
1.191 harris41 10749:
10750: =item *
10751:
1.243 albertel 10752: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10753: all args are optional
1.191 harris41 10754:
10755: =item *
10756:
1.717 albertel 10757: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10758: dumps the complete (or key matching regexp) namespace into a hash
10759: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10760: normally &store()ed into
10761:
10762: $range should be either an integer '100' (give me the first 100
10763: matching records)
10764: or be two integers sperated by a - with no spaces
10765: '30-50' (give me the 30th through the 50th matching
10766: records)
10767:
10768:
10769: =item *
10770:
10771: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10772: replaces a &store() version of data with a replacement set of data
10773: for a particular resource in a namespace passed in the $storehash hash
10774: reference
10775:
10776: =item *
10777:
1.243 albertel 10778: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10779: works very similar to store/cstore, but all data is stored in a
10780: temporary location and can be reset using tmpreset, $storehash should
10781: be a hash reference, returns nothing on success
1.191 harris41 10782:
10783: =item *
10784:
1.243 albertel 10785: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10786: similar to restore, but all data is stored in a temporary location and
10787: can be reset using tmpreset. Returns a hash of values on success,
10788: error string otherwise.
1.191 harris41 10789:
10790: =item *
10791:
1.243 albertel 10792: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10793: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10794:
10795: =item *
10796:
1.243 albertel 10797: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10798: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 10799:
10800: =item *
10801:
1.243 albertel 10802: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10803: namesp ($udom and $uname are optional)
1.191 harris41 10804:
10805: =item *
10806:
1.702 albertel 10807: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 10808: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 10809: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 10810:
1.702 albertel 10811: $range should be either an integer '100' (give me the first 100
10812: matching records)
10813: or be two integers sperated by a - with no spaces
10814: '30-50' (give me the 30th through the 50th matching
10815: records)
1.449 matthew 10816: =item *
10817:
10818: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10819: $store can be a scalar, an array reference, or if the amount to be
10820: incremented is > 1, a hash reference.
10821:
10822: ($udom and $uname are optional)
1.191 harris41 10823:
10824: =item *
10825:
1.243 albertel 10826: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10827: ($udom and $uname are optional)
1.191 harris41 10828:
10829: =item *
10830:
1.243 albertel 10831: cput($namespace,$storehash,$udom,$uname) : critical put
10832: ($udom and $uname are optional)
1.191 harris41 10833:
10834: =item *
10835:
1.748 albertel 10836: newput($namespace,$storehash,$udom,$uname) :
10837:
10838: Attempts to store the items in the $storehash, but only if they don't
10839: currently exist, if this succeeds you can be certain that you have
10840: successfully created a new key value pair in the $namespace db.
10841:
10842:
10843: Args:
10844: $namespace: name of database to store values to
10845: $storehash: hashref to store to the db
10846: $udom: (optional) domain of user containing the db
10847: $uname: (optional) name of user caontaining the db
10848:
10849: Returns:
10850: 'ok' -> succeeded in storing all keys of $storehash
10851: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10852: least <key> already existed in the db (other
10853: requested keys may also already exist)
1.967 bisitz 10854: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 10855: 'con_lost' -> unable to contact request server
10856: 'refused' -> action was not allowed by remote machine
10857:
10858:
10859: =item *
10860:
1.243 albertel 10861: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10862: reference filled in from namesp (encrypts the return communication)
10863: ($udom and $uname are optional)
1.191 harris41 10864:
10865: =item *
10866:
1.243 albertel 10867: log($udom,$name,$home,$message) : write to permanent log for user; use
10868: critical subroutine
10869:
1.806 raeburn 10870: =item *
10871:
1.860 raeburn 10872: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10873: array reference filled in from namespace found in domain level on either
10874: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 10875:
10876: =item *
10877:
1.860 raeburn 10878: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10879: domain level either on specified domain server ($uhome) or primary domain
10880: server ($udom and $uhome are optional)
1.806 raeburn 10881:
1.943 raeburn 10882: =item *
10883:
10884: get_domain_defaults($target_domain) : returns hash with defaults for
10885: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10886: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10887: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10888: Values are retrieved from cache (if current), or from domain's configuration.db
10889: (if available), or lastly from values in lonTabs/dns_domain,tab,
10890: or lonTabs/domain.tab.
10891:
10892: %domdefaults = &get_auth_defaults($target_domain);
10893:
1.243 albertel 10894: =back
10895:
10896: =head2 Network Status Functions
10897:
10898: =over 4
1.191 harris41 10899:
10900: =item *
10901:
10902: dirlist($uri) : return directory list based on URI
10903:
10904: =item *
10905:
1.243 albertel 10906: spareserver() : find server with least workload from spare.tab
10907:
1.986 foxr 10908:
10909: =item *
10910:
10911: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10912: if there is no corresponding loncapa host.
10913:
1.243 albertel 10914: =back
10915:
1.986 foxr 10916:
1.243 albertel 10917: =head2 Apache Request
10918:
10919: =over 4
1.191 harris41 10920:
10921: =item *
10922:
1.243 albertel 10923: ssi($url,%hash) : server side include, does a complete request cycle on url to
10924: localhost, posts hash
10925:
10926: =back
10927:
10928: =head2 Data to String to Data
10929:
10930: =over 4
1.191 harris41 10931:
10932: =item *
10933:
1.243 albertel 10934: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10935: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 10936:
10937: =item *
10938:
1.243 albertel 10939: hashref2str($hashref) : convert a hashref into a string complete with
10940: escaping and '=' and '&' separators, supports elements that are
10941: arrayrefs and hashrefs
1.191 harris41 10942:
10943: =item *
10944:
1.243 albertel 10945: arrayref2str($arrayref) : convert an arrayref into a string complete
10946: with escaping and '&' separators, supports elements that are arrayrefs
10947: and hashrefs
1.191 harris41 10948:
10949: =item *
10950:
1.243 albertel 10951: str2hash($string) : convert string to hash using unescaping and
10952: splitting on '=' and '&', supports elements that are arrayrefs and
10953: hashrefs
1.191 harris41 10954:
10955: =item *
10956:
1.243 albertel 10957: str2array($string) : convert string to hash using unescaping and
10958: splitting on '&', supports elements that are arrayrefs and hashrefs
10959:
10960: =back
10961:
10962: =head2 Logging Routines
10963:
10964: =over 4
10965:
10966: These routines allow one to make log messages in the lonnet.log and
10967: lonnet.perm logfiles.
1.191 harris41 10968:
10969: =item *
10970:
1.243 albertel 10971: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 10972:
10973: =item *
10974:
1.243 albertel 10975: logthis() : append message to the normal lonnet.log file, it gets
10976: preiodically rolled over and deleted.
1.191 harris41 10977:
10978: =item *
10979:
1.243 albertel 10980: logperm() : append a permanent message to lonnet.perm.log, this log
10981: file never gets deleted by any automated portion of the system, only
10982: messages of critical importance should go in here.
10983:
10984: =back
10985:
10986: =head2 General File Helper Routines
10987:
10988: =over 4
1.191 harris41 10989:
10990: =item *
10991:
1.481 raeburn 10992: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10993: (a) files in /uploaded
10994: (i) If a local copy of the file exists -
10995: compares modification date of local copy with last-modified date for
10996: definitive version stored on home server for course. If local copy is
10997: stale, requests a new version from the home server and stores it.
10998: If the original has been removed from the home server, then local copy
10999: is unlinked.
11000: (ii) If local copy does not exist -
11001: requests the file from the home server and stores it.
11002:
11003: If $caller is 'uploadrep':
11004: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11005: for request for files originally uploaded via DOCS.
11006: - returns 'ok' if fresh local copy now available, -1 otherwise.
11007:
11008: Otherwise:
11009: This indicates a call from the content generation phase of the request.
11010: - returns the entire contents of the file or -1.
11011:
11012: (b) files in /res
11013: - returns the entire contents of a file or -1;
11014: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11015:
1.712 albertel 11016:
11017: =item *
11018:
11019: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11020: reference
11021:
11022: returns either a stat() list of data about the file or an empty list
11023: if the file doesn't exist or couldn't find out about it (connection
11024: problems or user unknown)
11025:
1.191 harris41 11026: =item *
11027:
1.243 albertel 11028: filelocation($dir,$file) : returns file system location of a file
11029: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11030: directory that relative $file lookups are to looked in ($dir of /a/dir
11031: and a file of ../bob will become /a/bob)
1.191 harris41 11032:
11033: =item *
11034:
11035: hreflocation($dir,$file) : returns file system location or a URL; same as
11036: filelocation except for hrefs
11037:
11038: =item *
11039:
11040: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11041:
1.243 albertel 11042: =back
11043:
1.608 albertel 11044: =head2 Usererfile file routines (/uploaded*)
11045:
11046: =over 4
11047:
11048: =item *
11049:
11050: userfileupload(): main rotine for putting a file in a user or course's
11051: filespace, arguments are,
11052:
1.620 albertel 11053: formname - required - this is the name of the element in $env where the
1.608 albertel 11054: filename, and the contents of the file to create/modifed exist
1.620 albertel 11055: the filename is in $env{'form.'.$formname.'.filename'} and the
11056: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11057: coursedoc - if true, store the file in the course of the active role
11058: of the current user
11059: subdir - required - subdirectory to put the file in under ../userfiles/
11060: if undefined, it will be placed in "unknown"
11061:
11062: (This routine calls clean_filename() to remove any dangerous
11063: characters from the filename, and then calls finuserfileupload() to
11064: complete the transaction)
11065:
11066: returns either the url of the uploaded file (/uploaded/....) if successful
11067: and /adm/notfound.html if unsuccessful
11068:
11069: =item *
11070:
11071: clean_filename(): routine for cleaing a filename up for storage in
11072: userfile space, argument is:
11073:
11074: filename - proposed filename
11075:
11076: returns: the new clean filename
11077:
11078: =item *
11079:
11080: finishuserfileupload(): routine that creaes and sends the file to
11081: userspace, probably shouldn't be called directly
11082:
11083: docuname: username or courseid of destination for the file
11084: docudom: domain of user/course of destination for the file
11085: formname: same as for userfileupload()
11086: fname: filename (inculding subdirectories) for the file
11087:
11088: returns either the url of the uploaded file (/uploaded/....) if successful
11089: and /adm/notfound.html if unsuccessful
11090:
11091: =item *
11092:
11093: renameuserfile(): renames an existing userfile to a new name
11094:
11095: Args:
11096: docuname: username or courseid of destination for the file
11097: docudom: domain of user/course of destination for the file
11098: old: current file name (including any subdirs under userfiles)
11099: new: desired file name (including any subdirs under userfiles)
11100:
11101: =item *
11102:
11103: mkdiruserfile(): creates a directory is a userfiles dir
11104:
11105: Args:
11106: docuname: username or courseid of destination for the file
11107: docudom: domain of user/course of destination for the file
11108: dir: dir to create (including any subdirs under userfiles)
11109:
11110: =item *
11111:
11112: removeuserfile(): removes a file that exists in userfiles
11113:
11114: Args:
11115: docuname: username or courseid of destination for the file
11116: docudom: domain of user/course of destination for the file
11117: fname: filname to delete (including any subdirs under userfiles)
11118:
11119: =item *
11120:
11121: removeuploadedurl(): convience function for removeuserfile()
11122:
11123: Args:
11124: url: a full /uploaded/... url to delete
11125:
1.747 albertel 11126: =item *
11127:
11128: get_portfile_permissions():
11129: Args:
11130: domain: domain of user or course contain the portfolio files
11131: user: name of user or num of course contain the portfolio files
11132: Returns:
11133: hashref of a dump of the proper file_permissions.db
11134:
11135:
11136: =item *
11137:
11138: get_access_controls():
11139:
11140: Args:
11141: current_permissions: the hash ref returned from get_portfile_permissions()
11142: group: (optional) the group you want the files associated with
11143: file: (optional) the file you want access info on
11144:
11145: Returns:
1.749 raeburn 11146: a hash (keys are file names) of hashes containing
11147: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11148: values are XML containing access control settings (see below)
1.747 albertel 11149:
11150: Internal notes:
11151:
1.749 raeburn 11152: access controls are stored in file_permissions.db as key=value pairs.
11153: key -> path to file/file_name\0uniqueID:scope_end_start
11154: where scope -> public,guest,course,group,domains or users.
11155: end -> UNIX time for end of access (0 -> no end date)
11156: start -> UNIX time for start of access
11157:
11158: value -> XML description of access control
11159: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11160: <start></start>
11161: <end></end>
11162:
11163: <password></password> for scope type = guest
11164:
11165: <domain></domain> for scope type = course or group
11166: <number></number>
11167: <roles id="">
11168: <role></role>
11169: <access></access>
11170: <section></section>
11171: <group></group>
11172: </roles>
11173:
11174: <dom></dom> for scope type = domains
11175:
11176: <users> for scope type = users
11177: <user>
11178: <uname></uname>
11179: <udom></udom>
11180: </user>
11181: </users>
11182: </scope>
11183:
11184: Access data is also aggregated for each file in an additional key=value pair:
11185: key -> path to file/file_name\0accesscontrol
11186: value -> reference to hash
11187: hash contains key = value pairs
11188: where key = uniqueID:scope_end_start
11189: value = UNIX time record was last updated
11190:
11191: Used to improve speed of look-ups of access controls for each file.
11192:
11193: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11194:
11195: modify_access_controls():
11196:
11197: Modifies access controls for a portfolio file
11198: Args
11199: 1. file name
11200: 2. reference to hash of required changes,
11201: 3. domain
11202: 4. username
11203: where domain,username are the domain of the portfolio owner
11204: (either a user or a course)
11205:
11206: Returns:
11207: 1. result of additions or updates ('ok' or 'error', with error message).
11208: 2. result of deletions ('ok' or 'error', with error message).
11209: 3. reference to hash of any new or updated access controls.
11210: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11211: key = integer (inbound ID)
11212: value = uniqueID
1.747 albertel 11213:
1.608 albertel 11214: =back
11215:
1.243 albertel 11216: =head2 HTTP Helper Routines
11217:
11218: =over 4
11219:
1.191 harris41 11220: =item *
11221:
11222: escape() : unpack non-word characters into CGI-compatible hex codes
11223:
11224: =item *
11225:
11226: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11227:
1.243 albertel 11228: =back
11229:
11230: =head1 PRIVATE SUBROUTINES
11231:
11232: =head2 Underlying communication routines (Shouldn't call)
11233:
11234: =over 4
11235:
11236: =item *
11237:
11238: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11239:
11240: =item *
11241:
11242: reply() : uses subreply to send a message to remote machine, logs all failures
11243:
11244: =item *
11245:
11246: critical() : passes a critical message to another server; if cannot
11247: get through then place message in connection buffer directory and
11248: returns con_delayed, if incapable of saving message, returns
11249: con_failed
11250:
11251: =item *
11252:
11253: reconlonc() : tries to reconnect lonc client processes.
11254:
11255: =back
11256:
11257: =head2 Resource Access Logging
11258:
11259: =over 4
11260:
11261: =item *
11262:
11263: flushcourselogs() : flush (save) buffer logs and access logs
11264:
11265: =item *
11266:
11267: courselog($what) : save message for course in hash
11268:
11269: =item *
11270:
11271: courseacclog($what) : save message for course using &courselog(). Perform
11272: special processing for specific resource types (problems, exams, quizzes, etc).
11273:
1.191 harris41 11274: =item *
11275:
11276: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11277: as a PerlChildExitHandler
1.243 albertel 11278:
11279: =back
11280:
11281: =head2 Other
11282:
11283: =over 4
11284:
11285: =item *
11286:
11287: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11288:
11289: =back
11290:
11291: =cut
1.877 foxr 11292:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>